從 main.jsp 跳轉到 CategoryServlet 時,瀏覽器報 405 - HTTP method GET is not supported。Servlet 未覆寫 doGet/doPost,JSP 連結預設發送 GET 請求。
HttpServlet 預設 service() 會根據 HTTP 方法分派至 doGet/doPost 等。doPost 未覆寫 doGet,GET 請求會觸發父類 doGet,直接拋出 405。@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp); // 統一轉發至 doPost 邏輯
}
<form action="CategoryServlet" method="post">
<input type="submit" value="提交">
</form>
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 直接寫業務邏輯,忽略 HTTP 方法差異
}
@WebServlet("/category") 註解替代 web.xml,減少配置錯誤。@RequestMapping(method = {GET, POST}) 統一入口。