兩類參數定義對比
| 維度 | context-param | init-param |
| 作用域 | 整個 Web 應用 (ServletContext) | 單一 Servlet |
| 配置位置 | `` 直屬 | `` 內部 |
| 生命週期 | 應用啟動建立,關閉銷毀 | Servlet 初始化時讀取 |
| 典型用途 | 資料庫連線字串、全域設定檔路徑、共用常數 | 該 Servlet 專用參數(如分頁大小、模板路徑) |
| 獲取方式 | `getServletContext().getInitParameter("key")` | `getInitParameter("key")` (僅在 `init()` 可用) |
web.xml 範例
<web-app>
<!-- 應用級參數 -->
<context-param>
<param-name>appConfigPath</param-name>
<param-value>/WEB-INF/config/app.properties</param-value>
</context-param>
<servlet>
<servlet-name>MainServlet</servlet-name>
<servlet-class>com.example.MainServlet</servlet-class>
<!-- Servlet 級參數 -->
<init-param>
<param-name>pageSize</param-name>
<param-value>20</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
</web-app>
Servlet 取得範例
public class MainServlet extends HttpServlet {
@Override
public void init() throws ServletException {
// 1. Servlet 級參數 (僅在 init 可靠獲取)
String pageSize = getInitParameter("pageSize"); // "20"
System.out.println("pageSize = " + pageSize);
// 2. 應用級參數 (任何生命週期皆可獲取)
String configPath = getServletContext().getInitParameter("appConfigPath");
System.out.println("configPath = " + configPath);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
// 這裡也能取應用級參數
String path = getServletContext().getInitParameter("appConfigPath");
// 但**無法**直接取 Servlet 級參數 (除非在 init 時存為實例變數)
}
}
常見錯誤與最佳實踐
- 錯誤:在 `doGet` 中呼叫 `getInitParameter("pageSize")` → 永遠回傳 `null`。
- 正確:在 `init()` 存為 `this.pageSize = getInitParameter("pageSize");`,供後續方法使用。
- 現代替代:Spring `@Value("${app.config.path}")` 注入、`@ConfigurationProperties` 綁定,完全取代 web.xml 參數。
- Servlet 3.0+:可用 `@WebInitParam` 註解替代 XML:
`@WebServlet(urlPatterns="/main", initParams=@WebInitParam(name="pageSize", value="20"))`