首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java Web request.getParameter 空指針異常:參數缺失導致 getBytes 拋 NPE 的排查與防御編程

     編輯:程式設計疑難解答

錯誤代碼片段

String page = new String(request.getParameter("page").getBytes("iso-8859-1"), "utf-8");
String name = new String(request.getParameter("name").getBytes("iso-8859-1"), "utf-8");
if (name.equals("find")) {  // 此處拋 NullPointerException
    System.out.println("執行 find 函數");
}

根因:請求中缺少 name 參數

  • request.getParameter("name") 返回 null(參數不存在)。
  • 對 null 調用 .getBytes(...) → NullPointerException。
  • 異常拋出點在 getBytes,但堆疊跟蹤可能指向後續 name.equals 行(取決於 JIT 優化)。

修復方案:防御性非空判斷

String nameParam = request.getParameter("name");
if (nameParam == null) {
    // 記錄日誌、返回錯誤頁、或設置默認值
    nameParam = "";
}
String name = new String(nameParam.getBytes("iso-8859-1"), "utf-8");

if ("find".equals(name)) {  // 推薦常量在前,避免 NPE
    System.out.println("執行 find 函數");
}

編碼轉換最佳實踐(Tomcat 8+)

現代 Servlet 容器已正確處理 UTF-8,通常無需手動 iso-8859-1 轉碼:

  1. GET 請求:在 server.xml <Connector> 添加 URIEncoding="UTF-8"。
  2. POST 請求:在 Filter 中設置 request.setCharacterEncoding("UTF-8")(必須在首次讀取參數前調用)。
  3. 之後直接 request.getParameter("name") 即得正確字符串。

統一參數獲取工具類

public class ParamUtil {
    public static String getUtf8(HttpServletRequest req, String name, String def) {
        String val = req.getParameter(name);
        return (val != null) ? val : def;
    }
    public static int getInt(HttpServletRequest req, String name, int def) {
        String val = req.getParameter(name);
        try { return val != null ? Integer.parseInt(val) : def; }
        catch (NumberFormatException e) { return def; }
    }
}

// 使用
String name = ParamUtil.getUtf8(request, "name", "");
if ("find".equals(name)) { ... }

總結檢查清單

  1. ✅ 所有 getParameter 結果先判 null 再調用方法。
  2. ✅ 字符串比較用 "constant".equals(var) 模式。
  3. ✅ 配置容器 UTF-8 編碼,移除手動轉碼邏輯。
  4. ✅ 封裝工具類統一參數獲取與類型轉換。

「參數可能為 null」是 Web 開發的鐵律 —— 守住邊界,才能寫出不崩潰的 Controller。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved