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 函數");
}
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 函數");
}
現代 Servlet 容器已正確處理 UTF-8,通常無需手動 iso-8859-1 轉碼:
server.xml <Connector> 添加 URIEncoding="UTF-8"。request.setCharacterEncoding("UTF-8")(必須在首次讀取參數前調用)。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)) { ... }
getParameter 結果先判 null 再調用方法。"constant".equals(var) 模式。「參數可能為 null」是 Web 開發的鐵律 —— 守住邊界,才能寫出不崩潰的 Controller。