萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 正則表達式實戰:防範 SQL 注入的用戶登入驗證範例

為何需要正則驗證?

用戶輸入若未經過濾,攻擊者可透過 ' OR '1'='1 等語句繞過驗證。伺服端以正則表達式限制輸入字符集(僅允許字母數字),是第一道防線。

完整代碼實現

bd.jsp - 整合表單與驗證邏輯

<%@ page contentType="text/html;charset=gb2312" %>
<%!
  // 正則驗證方法:僅允許 A-Z, a-z, 0-9
  private boolean regex(String str) {
      java.util.regex.Pattern p = java.util.regex.Pattern.compile("[^0-9A-Za-z]");
      java.util.regex.Matcher m = p.matcher(str);
      return !m.find(); // 找到非法字符返回 false
  }
%>
<html>
<head><title>信息輸入表單</title></head>
<body>
<form action="bd.jsp" method="get">
  <div align="center">
    <font color="#FF0000">數據只能為 a-z, A-Z, 0-9 的字符</font>
    <table border="1">
      <tr>
        <td bgcolor="yellow">用戶</td>
        <td><input name="name" type="text" id="name"></td>
      </tr>
      <tr>
        <td bgcolor="yellow">密碼</td>
        <td><input name="pass" type="password" id="pass"></td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input name="submit" type="submit" value="確定">
          <input name="reset" type="reset" value="取消">
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">消息提示
        <%
          String name = request.getParameter("name");
          String pass = request.getParameter("pass");
          if (name == null) name = "我是非法的字符";
          if (pass == null) pass = "我是非法的字符";

          if (!regex(name)) {
              out.print("用戶名只能是 a-z, A-Z, 0-9 的字符");
              return;
          }
          out.print("恭喜您的數據錄入合法了。<br>您錄入的名字是:" + name + "<br>您錄入的密碼是:" + pass);
        %>
        </td>
      </tr>
    </table>
  </div>
</form>
</body>
</html>

核心邏輯解析

  • Pattern.compile("[^0-9A-Za-z]"):匹配非字母數字的字符
  • m.find():若找到匹配,表示含非法字符
  • 驗證失敗時 return 中斷頁面後續渲染

最佳實踐建議

  1. 永遠在伺服端驗證,前端 JS 驗證可繞過
  2. 實務上應改用 PreparedStatement 參數化查詢,從根源杜絕 SQL 注入
  3. 密碼欄位建議使用 type="password" 並配合 HTTPS 傳輸
  4. 正則可擴展為 ^[a-zA-Z0-9]{6,20}$ 限制長度與字符集
copyright © 萬盛學電腦網 all rights reserved