JAVA學(xué)習(xí)點(diǎn)點(diǎn)滴滴

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

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

          2006年2月18日 #

          創(chuàng)建型模式

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

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

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

          建造模式:將產(chǎn)品的內(nèi)部表象和產(chǎn)品的生成過(guò)程分割開(kāi)來(lái),從而使一個(gè)建造過(guò)程生成具有不同的內(nèi)部表象的產(chǎn)品對(duì)象。建造模式使得產(chǎn)品內(nèi)部表象可以獨(dú)立的變化,客戶不必知道產(chǎn)品內(nèi)部組成的細(xì)節(jié)。建造模式可以強(qiáng)制實(shí)行一種分步驟進(jìn)行的建造過(guò)程。

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

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

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

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

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

          單例模式:?jiǎn)卫J酱_保某一個(gè)類只有一個(gè)實(shí)例,而且自行實(shí)例化并向整個(gè)系統(tǒng)提供這個(gè)實(shí)例單例模式。單例模式只應(yīng)在有真正的“單一實(shí)例”的需求時(shí)才可使用。

          結(jié)構(gòu)型模式

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

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

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

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

          8、COMPOSITE—Mary今天過(guò)生日?!拔疫^(guò)生日,你要送我一件禮物?!薄班?,好吧,去商店,你自己挑?!薄斑@件T恤挺漂亮,買,這條裙子好看,買,這個(gè)包也不錯(cuò),買?!薄拔?,買了三件了呀,我只答應(yīng)送一件禮物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻煩你包起來(lái)?!薄啊保琈M都會(huì)用Composite模式了,你會(huì)了沒(méi)有?

          合成模式:合成模式將對(duì)象組織到樹(shù)結(jié)構(gòu)中,可以用來(lái)描述整體與部分的關(guān)系。合成模式就是一個(gè)處理對(duì)象的樹(shù)結(jié)構(gòu)的模式。合成模式把部分與整體的關(guān)系用樹(shù)結(jié)構(gòu)表示出來(lái)。合成模式使得客戶端把一個(gè)個(gè)單獨(dú)的成分對(duì)象和由他們復(fù)合而成的合成對(duì)象同等看待。

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

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

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

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

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

          享元模式:FLYWEIGHT在拳擊比賽中指最輕量級(jí)。享元模式以共享的方式高效的支持大量的細(xì)粒度對(duì)象。享元模式能做到共享的關(guān)鍵是區(qū)分內(nèi)蘊(yùn)狀態(tài)和外蘊(yùn)狀態(tài)。內(nèi)蘊(yùn)狀態(tài)存儲(chǔ)在享元內(nèi)部,不會(huì)隨環(huán)境的改變而有所不同。外蘊(yùn)狀態(tài)是隨環(huán)境的改變而改變的。外蘊(yùn)狀態(tài)不能影響內(nèi)蘊(yùn)狀態(tài),它們是相互獨(dú)立的。將可以共享的狀態(tài)和不可以共享的狀態(tài)從常規(guī)類中區(qū)分開(kāi)來(lái),將不可以共享的狀態(tài)從類里剔除出去??蛻舳瞬豢梢灾苯觿?chuàng)建被共享的對(duì)象,而應(yīng)當(dāng)使用一個(gè)工廠對(duì)象負(fù)責(zé)創(chuàng)建被共享的對(duì)象。享元模式大幅度的降低內(nèi)存中對(duì)象的數(shù)量。

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

          代理模式:代理模式給某一個(gè)對(duì)象提供一個(gè)代理對(duì)象,并由代理對(duì)象控制對(duì)源對(duì)象的引用。代理就是一個(gè)人或一個(gè)機(jī)構(gòu)代表另一個(gè)人或者一個(gè)機(jī)構(gòu)采取行動(dòng)。某些情況下,客戶不想或者不能夠直接引用一個(gè)對(duì)象,代理對(duì)象可以在客戶和目標(biāo)對(duì)象直接起到中介的作用??蛻舳朔直娌怀龃碇黝}對(duì)象與真實(shí)主題對(duì)象。代理模式可以并不知道真正的被代理對(duì)象,而僅僅持有一個(gè)被代理對(duì)象的接口,這時(shí)候代理對(duì)象不能夠創(chuàng)建被代理對(duì)象,被代理對(duì)象必須有系統(tǒng)的其他角色代為創(chuàng)建并傳入。

          行為模式

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

          責(zé)任鏈模式:在責(zé)任鏈模式中,很多對(duì)象由每一個(gè)對(duì)象對(duì)其下家的引用而接

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

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

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

          解釋器模式:給定一個(gè)語(yǔ)言后,解釋器模式可以定義出其文法的一種表示,并同時(shí)提供一個(gè)解釋器??蛻舳丝梢允褂眠@個(gè)解釋器來(lái)解釋這個(gè)語(yǔ)言中的句子。解釋器模式將描述怎樣在有了一個(gè)簡(jiǎn)單的文法后,使用模式設(shè)計(jì)解釋這些語(yǔ)句。在解釋器模式里面提到的語(yǔ)言是指任何解釋器對(duì)象能夠解釋的任何組合。在解釋器模式中需要定義一個(gè)代表文法的命令類的等級(jí)結(jié)構(gòu),也就是一系列的組合規(guī)則。每一個(gè)命令對(duì)象都有一個(gè)解釋方法,代表對(duì)命令對(duì)象的解釋。命令對(duì)象的等級(jí)結(jié)構(gòu)中的對(duì)象的任何排列組合都是一個(gè)語(yǔ)言。

          ?

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

          Mary:“想要我跟你結(jié)婚,得答應(yīng)我的條件”

          我:“什么條件我都答應(yīng),你說(shuō)吧”

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

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

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

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

          Mary:“你的小弟弟必須要有50cm長(zhǎng)”

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

          ……

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          轉(zhuǎn)http://java.ccidnet.com/art/3749/20060622/586221_3.html

          ?

          posted @ 2007-01-27 23:05 海思 閱讀(268) | 評(píng)論 (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

        1. Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
        2. 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).

        3. 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).

        4. 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.

        5. 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

        6. posted @ 2007-01-21 16:19 海思 閱讀(482) | 評(píng)論 (0)編輯 收藏

          跨越邊界: JavaScript 語(yǔ)言特性

          研究編程語(yǔ)言中的“丑小鴨”

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

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

          未顯示需要 JavaScript 的文檔選項(xiàng)

          樣例代碼


          拓展 Tomcat 應(yīng)用

          下載 IBM 開(kāi)源 J2EE 應(yīng)用服務(wù)器 WAS CE 新版本 V1.1


          級(jí)別: 初級(jí)

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

          2007 年 1 月 18 日

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

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

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

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

          關(guān)于這個(gè)系列

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

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

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

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

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

          • 靈活的對(duì)象模型:JavaScript 的對(duì)象模型使用一種相對(duì)不常見(jiàn)的方式進(jìn)行繼承 —— 稱為原型 —— 而不是 Java 語(yǔ)言中更常見(jiàn)的基于類的對(duì)象模型。

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

          立即開(kāi)始

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

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



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

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

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



          圖 1. Hello, world
          Hello, World.

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



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

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



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




          回頁(yè)首


          高階函數(shù)

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



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

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



          圖 3. 操縱函數(shù)

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

          將函數(shù)用作函數(shù)的參數(shù),或?qū)⒑瘮?shù)作為值返回,這些概念屬于高階函數(shù)的領(lǐng)域。清單 4 對(duì) 清單 3 做了一點(diǎn)點(diǎn)修改,顯示了能返回函數(shù)的高階函數(shù):



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

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



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

          高階函數(shù)是函數(shù)式編程的基礎(chǔ),對(duì)比面向?qū)ο缶幊蹋瘮?shù)式編程代表了更高級(jí)別的抽象。但 JavaScript 的實(shí)力并不僅限于高階函數(shù)。JavaScript 的動(dòng)態(tài)類型就極為適合 UI 開(kāi)發(fā)。





          回頁(yè)首


          動(dòng)態(tài)類型

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

          • 必須提前聲明意圖,這常常會(huì)導(dǎo)致靈活性降低。例如,更改一個(gè) Java 類就會(huì)更改類的類型,因而必須重新編譯。對(duì)比之下,Ruby 允許開(kāi)放的類,但更改一個(gè) Java 類還是會(huì)更改類的類型。

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

          • 靜態(tài)語(yǔ)言的編譯-部署周期要比動(dòng)態(tài)語(yǔ)言的部署周期長(zhǎng),盡管一些工具可被用來(lái)在某種程度上緩解這一問(wèn)題。

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

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



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

          當(dāng)加載并執(zhí)行此應(yīng)用程序時(shí),會(huì)得到如圖 5 所示的結(jié)果:



          圖 5. 引入屬性
           引入屬性

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

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



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

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





          回頁(yè)首


          對(duì)象模型

          到目前為止,您應(yīng)該對(duì) JavaScript 有一個(gè)正確的評(píng)價(jià)了,它絕非只如一個(gè)玩具那么簡(jiǎn)單。事實(shí)上,很多人都使用過(guò)其對(duì)象模型創(chuàng)建過(guò)極為復(fù)雜、設(shè)計(jì)良好的面向?qū)ο筌浖?。但?duì)象模型尤其是用于繼承的對(duì)象模型又非您一貫認(rèn)為的那樣。

          Java 語(yǔ)言是基于類的。當(dāng)構(gòu)建應(yīng)用程序時(shí),也同時(shí)構(gòu)建了可以作為所有對(duì)象的模板的新類。然后調(diào)用 new 來(lái)實(shí)例化該模板,創(chuàng)建一個(gè)新對(duì)象。而在 JavaScript 中,所創(chuàng)建的是一個(gè)原型,此原型是一個(gè)實(shí)例,可以創(chuàng)建所有未來(lái)的對(duì)象。

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



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

          清單 7 的結(jié)果如圖 6 所示:



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

          對(duì)于 Java 開(kāi)發(fā)人員而言,清單 7 中的代碼看起來(lái)多少有點(diǎn)生疏和奇怪。實(shí)際上對(duì)于沒(méi)有親自構(gòu)建過(guò)對(duì)象的許多 JavaScript 開(kāi)發(fā)人員來(lái)說(shuō),這些代碼同樣看起來(lái)有點(diǎn)生疏和奇怪。也許,下面的解釋可以讓大家能夠更好地理解這段代碼。

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

          回到 清單 7。如您所見(jiàn),JavaScript 基于在 Animal 中指定的原型定義一個(gè)新對(duì)象:myAnimal。繼而可以使用原型中的屬性和函數(shù),甚或重定義函數(shù)和屬性。這種靈活性可能會(huì)讓 Java 開(kāi)發(fā)人員受不了,因?yàn)樗麄儾涣?xí)慣這種行為,但它的確是一種十分強(qiáng)大的模型。

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



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

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



          圖 7. 通過(guò)原型繼承
          繼承

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

          • JavaScript 基于原始的原型創(chuàng)建實(shí)例,該原型在構(gòu)造函數(shù)中定義。任何對(duì)方法或?qū)傩缘囊枚紩?huì)使用所生成的原始副本。

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

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

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





          回頁(yè)首


          結(jié)束語(yǔ)

          JavaScript 對(duì)象模型構(gòu)建在該語(yǔ)言的其他功能之上來(lái)支持大量的庫(kù),比如 Dojo(參見(jiàn) 參考資料)。這種靈活性讓每個(gè)框架能夠以一種精細(xì)的方式更改對(duì)象模型。在某種程度上,這種靈活性是一種極大的缺點(diǎn)。它可以導(dǎo)致可怕的互操作性問(wèn)題(盡管該語(yǔ)言的靈活性可以部分緩解這些問(wèn)題)。

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

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


          參考資料

          學(xué)習(xí)
          posted @ 2007-01-21 15:49 海思 閱讀(253) | 評(píng)論 (0)編輯 收藏

          1、取出剛剛插入(刪除)的數(shù)據(jù)SELECT 字段名 FROM INSERTED(DELETED)
          2、對(duì)于UPDATE實(shí)際上是先DELETE然后再INSERT所以如果想得到UPDATE前后的數(shù)據(jù)值,應(yīng)該先從DELETED取出,然后從INSERTED取出;
          3、IF UPDATE(列名)可以判斷更新或插入哪一個(gè)字段的值;
          4、@@ROWCOUNT可以判斷上一行查詢操作得到的列數(shù);
          5、給變量賦值用SET @ZQB = 13;
          6、察看是否有符合條件的記錄IF EXISTS (SELECT name FROM sysobjects WHERE name = 'reminder' AND type = 'TR');
          7、定義游標(biāo),如下:
          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--從游標(biāo)中取出數(shù)據(jù)
          WHILE @@fetch_status = 0--判斷是否到最后
          BEGIN
          UPDATE emp_mgr
          SET emp_mgr.NoOfReports = emp_mgr.NoOfReports + 1 -- Add 1 for newly
          WHERE emp_mgr.emp = @e -- added employee.

          FETCH NEXT FROM c1 INTO @e
          END
          CLOSE c1
          DEALLOCATE c1--刪除游標(biāo)引用

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

          matrixeditor 發(fā)表于 2005-07-28 11:06:41
          作者:Matrixeditor???? 來(lái)源:BEA dev2dev
          評(píng)論數(shù):4 點(diǎn)擊數(shù):6,815???? 投票總得分:8 投票總?cè)舜?3
          關(guān)鍵字:

          摘要:

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


          安全管理對(duì)象
          ?????? Acegi安全系統(tǒng)目前支持兩類安全管理對(duì)象。
          ?????? 第一類的安全管理對(duì)象管理AOP Alliance的MethodInvocation,開(kāi)發(fā)人員可以用它來(lái)保護(hù)Spring容器中的業(yè)務(wù)對(duì)象。為了使Spring管理的Bean可以作為MethodInvocation來(lái)使用,Bean可以通過(guò)ProxyFactoryBean和BeanNameAutoProxyCreator來(lái)管理,就像在Spring的事務(wù)管理一樣使用。
          ?????? 第二類是FilterInvocation。它用過(guò)濾器(Filter)來(lái)創(chuàng)建,并簡(jiǎn)單地包裝了HTTP的ServletRequest,ServletResponse和FilterChain。FilterInvocation可以用來(lái)保護(hù)HTTP資源。通常,開(kāi)發(fā)人員并不需要了解它的工作機(jī)制,因?yàn)樗麄冎恍枰獙ilter加入web.xml,Acegi安全系統(tǒng)就可以工作了。

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


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

          ??????下面來(lái)看一個(gè)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的一個(gè)實(shí)現(xiàn)類。它包含了兩個(gè)管理器,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>


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

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

          安全攔截器
          ??攔截器如何工作
          ??MethodInvocation攔截器
          ??FilterInvocation攔截器
          認(rèn)證
          ??認(rèn)證請(qǐng)求
          ??認(rèn)證管理器
          ??Authentication Provider
          授權(quán)
          ??Access Decision Manager
          ??Voting Decision Manager
          ??授權(quán)管理推薦
          ContextHolder的用戶接口
          ??用戶接口目標(biāo)
          ??HTTP會(huì)話認(rèn)證
          ??HTTP Basic認(rèn)證

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

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

           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
          ????????

          ??首先,是設(shè)置root,格式為 log4j.rootLogger=[level],appenderName, ...,其中l(wèi)evel就是設(shè)置需要輸出信息的級(jí)別,后面是appender的輸出的目的地,appenderName就是指定日志信息輸出到哪個(gè)地方。您可以同時(shí)指定多個(gè)輸出目的地。配置日志信息輸出目的地Appender,其語(yǔ)法為
          ??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(控制臺(tái))
          ??org.apache.log4j.FileAppender(文件)
          ??org.apache.log4j.DailyRollingFileAppender(每天產(chǎn)生一個(gè)日志文件)
          ??org.apache.log4j.RollingFileAppender(文件大小到達(dá)指定尺寸的時(shí)候產(chǎn)生新文件)
          ??org.apache.log4j.WriterAppender(將日志信息以流格式發(fā)送到任意指定的地方)
          配置日志信息的格式(布局),其語(yǔ)法為:
          ??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(包含日志信息的級(jí)別和信息字符串),
          ??org.apache.log4j.TTCCLayout(包含日志產(chǎn)生的時(shí)間、線程、類別等等信息)

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

           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.");
          ????}
          ??}



          [簡(jiǎn)介]

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

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

          [基礎(chǔ)工作]
          在你的Web應(yīng)用的lib中添加Acegi下載包中的acegi-security.jar

          [web.xml]
          實(shí)現(xiàn)認(rèn)證和授權(quán)的最常用的方法是通過(guò)filter,Acegi亦是如此,通常Acegi需要在web.xml添加以下5個(gè)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.”,如希望深究的話,去看看源代碼應(yīng)該不難理解。

          再下來(lái)就是添加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>


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

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

          1) 首先,你的數(shù)據(jù)庫(kù)中必須具有保存用戶名和密碼的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) 添加訪問(wèn)你的數(shù)據(jù)庫(kù)的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>


          如果你需要對(duì)密碼加密,則在daoAuthenticationProvider中加入:<property name="passwordEncoder"><ref
          bean="passwordEncoder"/></property>,Acegi提供了幾種加密方法,詳細(xì)情況可看包
          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是登陸頁(yè)面,一個(gè)最簡(jiǎn)單的登錄頁(yè)面如下:

          <%@ 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>


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

          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是認(rèn)證失敗的頁(yè)面。

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

          <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",分別對(duì)頁(yè)面和方法進(jìn)行安全認(rèn)證管理,我這里介紹的只是利用
          FilterSecurityInterceptor對(duì)訪問(wèn)頁(yè)面的權(quán)限控制,除此之外,Acegi還提供了另外一個(gè)Interceptor――
          MethodSecurityInterceptor,它結(jié)合runAsManager可實(shí)現(xiàn)對(duì)對(duì)象中的方法的權(quán)限控制,使用方法可參看Acegi自帶的文檔
          和contact范例。

          [最后要說(shuō)的]
          本來(lái)以為只是說(shuō)明如何使用Acegi而已,應(yīng)該非常簡(jiǎn)單,但真正寫起來(lái)才發(fā)現(xiàn)想要條理清楚的理順?biāo)行枰腷ean還是很
          困難的,但愿我沒(méi)有遺漏太多東西,如果我的文章有什么遺漏或錯(cuò)誤的話,還請(qǐng)參看Acegi自帶的quick-start范例,但請(qǐng)
          注意,這個(gè)范例是不能直接拿來(lái)用的。
          分析和學(xué)習(xí)Spring中的jpetstore用戶管理
          ??存在用戶的系統(tǒng),必然需要用戶的登錄和認(rèn)證,今天就通過(guò)分析Spring中自帶的jpetstore的例子來(lái)學(xué)習(xí)一下如何實(shí)現(xiàn)在Spring構(gòu)架的系統(tǒng)中用戶登錄。
          1、首先從注冊(cè)用戶開(kāi)始,先看看jpetstore-servlet.xml中關(guān)于注冊(cè)用戶的bean定義,從定義命名中就可以看出下面這段就是注冊(cè)用戶的:
          ??
          <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的構(gòu)造函數(shù)中得到,原來(lái)為EditAccountForm;??
          2). EditoAccountForm.jsp中顯得非常亂,其實(shí)沒(méi)有多少難理解的地方,最主要的是這個(gè)form既是添加新用戶的,又是編輯用戶信息的,所以顯得有點(diǎn)亂糟糟的。
          2、添加好了新用戶,接下來(lái)看看如何登錄,在jpetstore-servlet中發(fā)現(xiàn)這兩個(gè)相關(guān)bean定義,如下:
          ??
          <bean name="/shop/signon.do" class="org.springframework.samples.jpetstore.web.spring.SignonController">
          ????<property name="petStore"><ref bean="petStore"/></property>
          ??</bean>
          ??<bean name="/shop/signonForm.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
          ????<property name="viewName"><value>SignonForm</value></property>
          ??</bean>

          1). 第二個(gè)bean是在運(yùn)行時(shí)用戶輸入用戶名和密碼的form,叫做SignonForm,對(duì)于這個(gè) ParameterizableViewController,用文檔里的話說(shuō)這是最簡(jiǎn)單的Controller,其作用就是在運(yùn)行中指向 Controller而不是直接指向jsp文件,僅此而已。
          2). SignonForm.jsp,里面就是一個(gè)簡(jiǎn)單的form,其action就是第一個(gè)bean,即/shop/signon.do,最需要注意的是 signonForwardAction,其主要作用是forward到需要輸入用戶名和密碼的那個(gè)頁(yè)面上去,這個(gè)變量哪里來(lái)的呢?看看下面:
          ??
          <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>

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

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

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

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

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

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

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

          (該文轉(zhuǎn)載自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 海思 閱讀(467) | 評(píng)論 (0)編輯 收藏

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

          利用XMLBean輕輕松松讀寫XML

          作者:葉楓




          版權(quán)聲明:本文可以自由轉(zhuǎn)載,轉(zhuǎn)載時(shí)請(qǐng)務(wù)必以超鏈接形式標(biāo)明文章原始出處和作者信息及本聲明
          作者:葉楓(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]
          關(guān)鍵字:XML XMLBean Parser

          一、關(guān)于XML解析

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

          二、XMLBean簡(jiǎn)介

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

          三、準(zhǔn)備XMLBean和XML文檔

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


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

          <?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>


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

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

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

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

          </xb:config>


          四、XMLBean使用步驟

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

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

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

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

          ?????? 怎樣產(chǎn)生這個(gè)Schema文件呢? 如果對(duì)于熟悉XML的開(kāi)發(fā)人員,可以自己來(lái)
          ?????? 寫這個(gè)Schema文件,對(duì)于不熟悉XML的開(kāi)發(fā)人員,可以通過(guò)一些工具來(lái)完成.
          ?????? 比較有名的如XMLSPY和Stylus Studio都可以通過(guò)XML文件來(lái)生成Schema
          ?????? 文件. 加入我們已經(jīng)生成這個(gè)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來(lái)生成Java Classes

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

          ??????

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


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

          ?????? 在本文,我是這樣運(yùn)行的:
          ??????

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


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

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

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


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

          五、利用XMLBean讀XML文件

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

          ????新建一個(gè)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();
          ????}

          ????}
          ????


          ????運(yùn)行它,參看輸出結(jié)果:
          ????

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

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

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

          六、利用XMLBean寫XML文件

          ????利用XMLBean創(chuàng)建一個(gè)XML文檔也是一件輕而易舉的事.我們?cè)僭黾右粋€(gè)Method,
          ????請(qǐng)看一下的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();
          ????}
          ????

          ????運(yùn)行,打開(kāi)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文件

          ????我們?cè)僭黾右粋€(gè)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");
          ????}
          ????

          ????運(yùn)行之后,我們將會(huì)看到客戶編號(hào)為3的客戶的lastname已經(jīng)改為last.

          八、利用XMLBean刪除一個(gè)customer

          ????再增加一個(gè)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);
          ????}

          ????????
          運(yùn)行,我們將會(huì)看到客戶編號(hào)為3的客戶的資料已經(jīng)被刪除.

          九、查詢XML

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



          十、結(jié)束語(yǔ)
          ????XMLBean能幫助我們輕易讀寫XML,這將有助于我們降低XML的學(xué)習(xí)和使用,有了這個(gè)基礎(chǔ),
          ????開(kāi)發(fā)人員將為學(xué)習(xí)更多地XML相關(guān)技術(shù)和Web Services,JMS等其他J2EE技術(shù)打下良好地基礎(chǔ).


          關(guān)于作者:
          葉楓:熱愛(ài)Java和Oracle. 在軟件開(kāi)發(fā)有近10年, 目前在國(guó)外一家美國(guó)大公司擔(dān)任SA, 負(fù)責(zé)技術(shù)研究。作者Blog:http://blog.matrix.org.cn/page/葉楓
          posted @ 2006-12-21 23:10 海思 閱讀(274) | 評(píng)論 (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摘要:?jiǎn)吸c(diǎn)登錄(SSO)的技術(shù)被越來(lái)越廣泛地運(yùn)用到各個(gè)領(lǐng)域的軟件系統(tǒng)當(dāng)中。本...  閱讀全文
          posted @ 2006-12-21 22:42 海思 閱讀(400) | 評(píng)論 (0)編輯 收藏

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

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

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

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

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

            2)計(jì)算?!=mod(S,11)

            3)通過(guò)模得到對(duì)應(yīng)的校驗(yàn)碼 :012345678910 驗(yàn)碼:10X98765432

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

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

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

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

            privateint[]ai=newint[18];

            publicIDCard(){}

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

            //getverifypublicStringgetVerify(Stringeightcardid){intremaining=0;

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

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

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

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

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

            }

            測(cè)試代碼:使用的單元測(cè)試工具是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 海思 閱讀(378) | 評(píng)論 (0)編輯 收藏

          說(shuō)明:復(fù)制表(只復(fù)制結(jié)構(gòu),源表名:a  新表名:b)
          SQL:  select  *  into  b  from  a  where  1<>1
          說(shuō)明:拷貝表(拷貝數(shù)據(jù),源表名:a  目標(biāo)表名:b)
          SQL:  insert  into  b(a,  b,  c)  select  d,e,f  from  b;
          說(shuō)明:顯示文章、提交人和最后回復(fù)時(shí)間
          SQL:  select  a.title,a.username,b.adddate  from  table  a,(select  max(adddate)  adddate  from  table  where  table.title=a.title)  b
          說(shuō)明:外連接查詢(表名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
          說(shuō)明:日程安排提前五分鐘提醒
          SQL:    select  *  from  日程安排  where  datediff('minute',f開(kāi)始時(shí)間,getdate())>5
          說(shuō)明:兩張關(guān)聯(lián)表,刪除主表中已經(jīng)在副表中沒(méi)有的信息
          SQL:    
          delete  from  info  where  not  exists  (  select  *  from  infobz  where  info.infid=infobz.infid  )  
          說(shuō)明:--
          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
          說(shuō)明:--
          SQL:    
          select  *  from  studentinfo  where  not  exists(select  *  from  student  where  studentinfo.id=student.id)  and  系名稱='"&strdepartmentname&"'  and  專業(yè)名稱='"&strprofessionname&"'  order  by  性別,生源地,高考總成績(jī)
          說(shuō)明:
          從數(shù)據(jù)庫(kù)中去一年的各單位電話費(fèi)統(tǒng)計(jì)(電話費(fèi)定額賀電化肥清單兩個(gè)表來(lái)源)
          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')
          說(shuō)明:四表聯(lián)查問(wèn)題:
          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  .....

          說(shuō)明:得到表中最小的未使用的ID號(hào)
          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 海思 閱讀(195) | 評(píng)論 (0)編輯 收藏

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

          3.MFC  Windows  程序設(shè)計(jì)(第二版)
          英文版:http://www.jka77.com/book/progmfc2.chm
          中文版:暫無(wú),制作中...
          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++經(jīng)典對(duì)話系列
          中文:http://www.jka77.com/book/cvst_cn.chm

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

          13.數(shù)據(jù)結(jié)構(gòu)  C++  語(yǔ)言描述(中文版)
          http://www.code-labs.com/manual/c_c015.zip

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

          15.C++標(biāo)準(zhǔn)庫(kù)英文版
          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:協(xié)議
          ftp://202.204.4.161/學(xué)習(xí)資料/TCPIP/TCP-IP詳解卷1:協(xié)議.pdf

          18.TCP-IP詳解卷2:實(shí)現(xiàn)
          ftp://202.204.4.161/學(xué)習(xí)資料/TCPIP/TCP-IP詳解卷3:TCP事務(wù)協(xié)議,HTTP,NNTP.pdf

          19.TCP-IP詳解卷3:TCP事務(wù)協(xié)議
          ftp://202.204.4.161/學(xué)習(xí)資料/TCPIP/TCP-IP詳解卷2:實(shí)現(xiàn).pdf

          20.實(shí)用算法的分析與程序設(shè)計(jì)
          ftp://202.204.8.10/[4]%20編程資源/[%20書籍資料%20]/[算法與數(shù)據(jù)結(jié)構(gòu)]/實(shí)用算法的分析與程序設(shè)計(jì).rar

          21.vc++技術(shù)內(nèi)幕第四版  (潘愛(ài)民)
          ftp://210.32.157.56/課件/c++primer/vc++技術(shù)內(nèi)幕IV(潘愛(ài)民).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程式開(kāi)發(fā)設(shè)計(jì)指南-Petzoldi著  余孟學(xué)  譯
          中文版: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  程序設(shè)計(jì)指南-候捷譯
          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技術(shù)內(nèi)幕第五版  http://www.helpwork.com/downdata  ...  k/vc++2/invcpp5.chm

          34.com技術(shù)內(nèi)幕
          http://www.helpwork.com/book/html/user/download.asp?id=1123

          35.com+技術(shù)內(nèi)幕
          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語(yǔ)言編程手冊(cè)
          下載地址:http://www.jka77.com/book/CL.chm

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

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

          41.Windows2000編程技術(shù)內(nèi)幕
          By  Mickey  Williams  機(jī)械工業(yè)出版社
          下載地址:ftp://ftp.frontfree.net/Pub/Books/C&C++/VC/Windows2000編程技術(shù)內(nèi)幕.rar

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

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

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

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

          46.C++標(biāo)準(zhǔn)程序庫(kù)
          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.程序設(shè)計(jì)實(shí)踐
          下載地址: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技術(shù)內(nèi)幕  (這本書俺不知道好不好:-))
          By  I  don't  Know
          下載地址:http://www.codestudy.net/book/download.asp?id=1254&sort=5

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

          53.  中國(guó)大百科全書·數(shù)學(xué)
          下載地址:ftp://ftp.math.nankai.edu.cn/Ebook/中國(guó)大百科全書/中國(guó)大百科全書·數(shù)學(xué).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高級(jí)編程技術(shù)》  
          http://www.dingbing.com/book/builder.zip

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

          63.《BORLAND  C++  BUILDER  實(shí)用培訓(xùn)教程》  
          http://202.101.232.120/book/open  ...  name=BC98_CB526.zip

          64.《Delphi高級(jí)開(kāi)發(fā)指南》  
          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深度歷險(xiǎn)-附書源碼》  
          http://www.pcbookcn.com/s10899bo  ...  elphi_sdlx_code.rar

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

          68.《Delphi7開(kāi)發(fā)指南》
          ftp://book:book@down.pcbookcn.com/pro/delphi/delphi7開(kāi)發(fā)指南.rar

          69.《Delphi6集成開(kāi)發(fā)環(huán)境》  
          ftp://book:book@down.pcbookcn.com/pro/delphi/Delphi6集成開(kāi)發(fā)環(huán)境.rar

          70.《Delphi6數(shù)據(jù)庫(kù)編程》  
          ftp://book:book@down.pcbookcn.com/pro/delphi/Delphi6數(shù)據(jù)庫(kù)編程.rar

          72.《Delphi5.xADO_MTS_COM+高級(jí)程序設(shè)計(jì)篇》
          ftp://book:book@down.pcbookcn.co  ...  lphi5.xADO_MTS_COM+高級(jí)程序設(shè)計(jì)篇.rar

          73.《VISUAL  BASIC  編程標(biāo)準(zhǔn)》  
          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  控件參考手冊(cè)》  
          http://www.easysea.com/diannao/download/prog/vb/kjck.zip

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

          77.《Visual  Basic  6.0  開(kāi)發(fā)寶典》  
          http://www.easysea.com/diannao/download/prog/vb/kfbd.zip

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

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

          80.《Visual  Basic  6開(kāi)發(fā)人員指南》  
          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開(kāi)發(fā)人員指南》  
          http://youth.dlmu.edu.cn/book/list_down.php?bkid=224

          84.《Win32的Internet函數(shù)說(shuō)明》  
          檔案大小:  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  參考手冊(cè)  》  
          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  程序開(kāi)發(fā)手冊(cè)》  
          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  類庫(kù)參考手冊(cè)》  
          http://www.easysea.com/diannao/download/prog/java/lkck.zip

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

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

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

          94.《掌握ACCESS開(kāi)發(fā)》  
          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  程序設(shè)計(jì)》  
          http://www.oradb.net/book/oracleproc.zip

          97.《Oracle8初學(xué)者指南》  
          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++高級(jí)編程》  
          http://www.easysea.com/diannao/download/prog/c/vcgj.zip
          posted @ 2006-02-22 22:03 海思 閱讀(343) | 評(píng)論 (0)編輯 收藏

          本文章對(duì):
          發(fā)送普通郵件,接受普通郵件
          發(fā)送帶有附件的郵件,接收帶有附件的郵件
          發(fā)送html形式的郵件,接受html形式的郵件
          [b[發(fā)送帶有圖片的郵件等做了一個(gè)總結(jié)。
          程序代碼:  
          程序代碼:

          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";
          //此段代碼用來(lái)發(fā)送普通電子郵件
          void jButton1_actionPerformed(ActionEvent e) {
          try
          {
          Properties props = new Properties();//獲取系統(tǒng)環(huán)境
          Authenticator auth = new Email_Autherticator();//進(jìn)行郵件服務(wù)器用戶認(rèn)證

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

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

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

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


          Transport.send(message);//發(fā)送郵件
          /* // 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);
          }
          }

          //此段代碼用來(lái)進(jìn)行服務(wù)器對(duì)用戶的認(rèn)證
          public class Email_Autherticator extends Authenticator
          {
          public Email_Autherticator()
          {
          super();
          }
          public PasswordAuthentication getPasswordAuthentication()
          {
          return new PasswordAuthentication(username,password);
          }
          }
          //該程序?yàn)榻邮锗]件
          void jButton2_actionPerformed(ActionEvent e) {
          try
          {
          Properties props = System.getProperties(); //獲取系統(tǒng)變量
          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后,取得一個(gè)文件夾,一般默認(rèn)的是INDEX
          folder.open(Folder.READ_WRITE);//READ_ONLY為打開(kāi)方式
          Message message[] = folder.getMessages();//從文件夾獲取郵件信息

          //可以用兩種方式去獲得郵件信息,getContent()用來(lái)獲得郵件的主體信息。而WriteTo()可以用來(lái)獲得郵件的全部信息,包括頭部信息
          // 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");

          //以下代碼用來(lái)獲得郵件的正文信息
          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);//最后刪除服務(wù)器端的郵件
          }
          //DELETED,ANSWERED,DRAFT,FLAGGED,RECENT,SEEN,USER
          folder.close(true);//true的話,徹底刪除已經(jīng)標(biāo)記為DELETE的郵件,如果為false的話,就不刪除
          store.close();//關(guān)閉
          }
          catch(Exception ej2)
          {
          System.out.println(ej2);
          }
          }

          void jButton4_actionPerformed(ActionEvent e) {
          try
          {//該程序?yàn)榛貜?fù)郵件
          Properties props = System.getProperties(); //獲取系統(tǒng)變量
          Authenticator auth = new Email_Autherticator(); //取得穃uFFFD衿魅現(xiàn)?
          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();//獲取郵件發(fā)信人的署名

          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();//關(guān)閉
          }
          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 
          //原理:可以將郵件看成有多個(gè)部分組成的,如正文是一個(gè)部分,附件也是一個(gè)部分,所以用BodyPart來(lái)設(shè)置郵件的格式
          程序代碼:  
          程序代碼:
          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");//此處設(shè)置郵件的附件
          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);
          }

          }
          //此段代碼用來(lái)發(fā)送帶有附件的郵件
          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");

          //以下代碼用來(lái)獲取郵件的主體信息
          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))))
          {

          //以下代碼將獲得的附件保存到當(dāng)前目錄下,以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();//獲得附件的大小,不一定很準(zhǔn)確。

          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();//關(guān)閉
          }
          catch(Exception ej2)
          {
          System.out.println(ej2);
          }
          }

          //此段代碼用來(lái)發(fā)送帶有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);
          //設(shè)置郵件正文
          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設(shè)置郵件的格式因?yàn)槭菐в衕tml文檔的,所以用text/html格式

          message.setSubject(mail_subject);
          // message.setText(mail_body);在使用message.setContent()時(shí)候,好象不能用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);
          }

          }

          //此段代碼用來(lái)發(fā)送帶有圖片的郵件
          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");
          //原理同發(fā)送附件一樣,將郵件看成有多個(gè)部分組成的,先設(shè)置每一個(gè)部分,然后再全部將它們合起來(lái)即可。
          //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);
          }

          }

          //該程序用來(lái)接受帶有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");

          //獲取郵件的信息,并且對(duì)其每一部分進(jìn)行操作
          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 海思 閱讀(427) | 評(píng)論 (0)編輯 收藏

          一、jsp連接Oracle8/8i/9i數(shù)據(jù)庫(kù)(用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為你的數(shù)據(jù)庫(kù)的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())  {%>  
          您的第一個(gè)字段內(nèi)容為:<%=rs.getString(1)%>  
          您的第二個(gè)字段內(nèi)容為:<%=rs.getString(2)%>  
          <%}%>  
          <%out.print("數(shù)據(jù)庫(kù)操作成功,恭喜你");%>  
          <%rs.close();  
          stmt.close();  
          conn.close();  
          %>  
          </body>  
          </html>  



          二、jsp連接Sql  Server7.0/2000數(shù)據(jù)庫(kù)  
          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為你的數(shù)據(jù)庫(kù)的  
          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())  {%>  
          您的第一個(gè)字段內(nèi)容為:<%=rs.getString(1)%>  
          您的第二個(gè)字段內(nèi)容為:<%=rs.getString(2)%>  
          <%}%>  
          <%out.print("數(shù)據(jù)庫(kù)操作成功,恭喜你");%>  
          <%rs.close();  
          stmt.close();  
          conn.close();  
          %>  
          </body>  
          </html>  



          三、jsp連接DB2數(shù)據(jù)庫(kù)  
          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為你的數(shù)據(jù)庫(kù)名  
          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())  {%>  
          您的第一個(gè)字段內(nèi)容為:<%=rs.getString(1)%>  
          您的第二個(gè)字段內(nèi)容為:<%=rs.getString(2)%>  
          <%}%>  
          <%out.print("數(shù)據(jù)庫(kù)操作成功,恭喜你");%>  
          <%rs.close();  
          stmt.close();  
          conn.close();  
          %>  
          </body>  
          </html>  



          四、jsp連接Informix數(shù)據(jù)庫(kù)  
          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為你的數(shù)據(jù)庫(kù)名  
          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())  {%>  
          您的第一個(gè)字段內(nèi)容為:<%=rs.getString(1)%>  
          您的第二個(gè)字段內(nèi)容為:<%=rs.getString(2)%>  
          <%}%>  
          <%out.print("數(shù)據(jù)庫(kù)操作成功,恭喜你");%>  
          <%rs.close();  
          stmt.close();  
          conn.close();  
          %>  
          </body>  
          </html>  



          五、jsp連接Access數(shù)據(jù)庫(kù)  
          <%@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  ("驅(qū)動(dòng)程序不存在");  
          }    
          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())  
          {  
          //*/////////////////////////顯示數(shù)據(jù)庫(kù)的內(nèi)容用于調(diào)試程序是用//  
          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 海思 閱讀(120) | 評(píng)論 (0)編輯 收藏

          主站蜘蛛池模板: 启东市| 保山市| 阿克陶县| 青田县| 彭水| 黑山县| 中方县| 丹阳市| 平顶山市| 古丈县| 筠连县| 蒲江县| 万山特区| 奇台县| 长岛县| 禹州市| 隆尧县| 南江县| 张家川| 珠海市| 阿图什市| 漳浦县| 武川县| 汉寿县| 阿拉善盟| 永州市| 辽阳市| 关岭| 南靖县| 龙海市| 镇平县| 渭源县| 东光县| 青冈县| 凭祥市| 来安县| 讷河市| 贡山| 怀集县| 海盐县| 扬州市|