絕大多數情況下,重寫 `doGet()` 和 `doPost()` 即可,不要重寫 `service()`。
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 處理 GET 請求
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 處理 POST 請求
}
// 無需重寫 service()
}
Servlet (interface)
↑
GenericServlet (abstract) — service(ServletRequest, ServletResponse)
↑
HttpServlet — service(ServletRequest, ServletResponse) [final]
service(HttpServletRequest, HttpServletResponse) [protected]
doGet, doPost, doPut, doDelete...