method="get" → 正常進入 doGet,輸出正常。method="post" → 頁面跳轉到 Servlet,但 System.out.println 無輸出,邏輯未執行。HttpServlet 預設:
doGet 處理 GET 請求doPost 處理 POST 請求@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("username");
System.out.println("servlet---" + name);
// 共同業務邏輯
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp); // 統一入口
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// POST 專屬邏輯:如修改資料、上傳檔案
String name = req.getParameter("username");
// ...
}
doPost 调用 doGet 是標準寫法。web.xml 或 @WebServlet 正確映射 URL。service() 會自動分派——它確實會,但前提是你**覆寫了對應的 doXxx 方法**。enctype="multipart/form-data" 導致檔案上傳失敗(另一問題)。POST 請求**必須覆寫 doPost**,否則 Servlet 容器不會執行你的業務代碼。最簡單做法:doPost 调用 doGet 統一處理。