Java防止SQL注入

來源:互聯網
上載者:User

1. 定義:

所謂SQL注入,就是通過把SQL命令插入到Web表單遞交或輸入欄位名或頁面請求的查詢字串,最終達到欺騙伺服器執行惡意的SQL命令。

2. 防止SQL注入的方法:

A:使用PreparedStatement代替Statement

   1)使用PreparedStatement 比Statement的代碼的可讀性和可維護性更好.
   2)PreparedStatement盡最大可能提高效能.
   3)最重要的一點是PreparedStatement極大地提高系統的安全性.

 sql="select * from admin where username=? and password=?"; PreparedStatement psmt= con.prepareStatement(sql); psmt.setString(1,username); psmt.setString(2,password); ResultSet rs = psmt.executeQuery(); if(rs.next){ rs.close(); con.close(); return false; } else{ rs.close(); con.close(); return true; }

B: 使用字串過濾

public static String filterContent(String content){   String flt ="'|and|exec|insert|select|delete|update|count|*|%                   |chr|mid|master|truncate|char|declare|;|or|-|+|,";   Stringfilter[] = flt.split("|"); for(int i=0;i<filter.length ; i++)    {      content.replace(filter[i], "");    }     return content;  }

或者使用Filter來過濾全域的表單參數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.