首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Servlet 核心接口解析:ServletConfig、ServletContext、GenericServlet 與 HttpServlet 體系

     編輯:Java 相關知識

核心接口與類關係圖

Servlet (接口)
  ↑ 實現
GenericServlet (抽象類) ← 實現 ServletConfig
  ↑ 繼承
HttpServlet (抽象類) ← 專為 HTTP 協議設計

ServletConfig vs ServletContext

接口作用域獲取方式典型用途
ServletConfig單個 ServletgetServletConfig()讀取 <init-param> 初始化參數
ServletContext整個 Web 應用 (Context)getServletContext()全局配置、資源訪問、屬性共享、RequestDispatcher

web.xml 中配置 Servlet 初始化參數

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.example.MyServlet</servlet-class>
  <init-param>
    <param-name>configKey</param-name>
    <param-value>configValue</param-value>
  </init-param>
</servlet>

在 Servlet 中獲取:getServletConfig().getInitParameter("configKey") 或繼承 GenericServlet 後直接 getInitParameter("configKey")。

生命週期方法詳解

1. init(ServletConfig config)

  • 由容器調用,僅一次。
  • GenericServlet 實現中保存 config 引用,並調用無參 init() 供子類重寫。
  • 子類通常重寫無參 init(),而非帶參版本。

2. service(ServletRequest req, ServletResponse res)

  • 每次請求調用一次。
  • HttpServlet 重寫 service,根據 req.getMethod() 分發到 doGet、doPost 等。
  • 若重寫了 service,則 doGet/doPost 失效,需自行分發。

3. destroy()

  • 容器卸載 Servlet 前調用,釋放資源。

HttpServlet 核心價值

  • 封裝 HTTP 協議細節:HttpServletRequest、HttpServletResponse。
  • 提供 doGet、doPost、doPut、doDelete、doHead、doOptions、doTrace 對應 REST 風格。
  • 自動處理 HEAD、TRACE 等方法默認行為。

開發建議

  1. 繼承 HttpServlet,重寫 doGet/doPost。
  2. 初始化邏輯放在無參 init(),資源清理放在 destroy()。
  3. 線程安全:Servlet 實例單例多線程共享,請勿在實例字段存儲請求級數據。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved