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

Servlet 登錄驗證失敗轉發錯誤頁:RequestDispatcher 必須 forward 而非僅 getRequestDispatcher

     編輯:程式設計疑難解答

問題代碼

public void doError(HttpServletRequest request, HttpServletResponse response, String str) 
        throws ServletException, IOException {
    request.setAttribute("problem", str);
    getServletConfig().getServletContext().getRequestDispatcher("/errorpage.jsp"); // 缺 forward
}

現象:驗證失敗時,頁面不跳轉,錯誤信息不顯示。

修正

public void doError(HttpServletRequest request, HttpServletResponse response, String str) 
        throws ServletException, IOException {
    request.setAttribute("problem", str);
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/errorpage.jsp");
    rd.forward(request, response); // 必須 forward
}

補充建議

  • 統一用 `getServletContext().getRequestDispatcher(path)`,避免 `getServletConfig()` 導致路徑解析異常。
  • 若需**重定向**(地址欄變化),用 `response.sendRedirect("/errorpage.jsp")`,但無法攜帶 request 屬性。
  • 開發階段建議在關鍵分支打斷點/日誌,確認 `doError` 是否被調用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved