Servlet 生命週期中 init() 僅執行一次。適用於:JDBC 連線池 (DataSource)、配置資訊、字典表等昂貴資源的初始化。
public class ControllerServlet extends HttpServlet {
private DataSource testDS;
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context ctx = new InitialContext();
testDS = (DataSource) ctx.lookup("jdbc/testDS"); // JNDI 查找一次,緩存供後續複用
} catch (NamingException e) { throw new ServletException(e); }
}
public DataSource getTestDS() { return testDS; }
}
開發期 reloadable="true 方便熱部署,但生產環境會導致類載入器頻繁掃描、內存洩漏風險。生產必須設為 false。
<%@ page session="false" %> 禁用自動創建。session.invalidate() 釋放。web.xml <session-timeout>),減少佔用記憶體。避免頻繁建立/關閉物理連線。配合策略一在 init() 緩存 DataSource,業務代碼直接 ds.getConnection()。
page 指令 buffer="16kb" autoFlush="true" 調整緩衝區。server.xml Connector 開啟 compression="on" compressableMimeType="text/html,text/xml,text/css,application/javascript"。Expires/Cache-Control 頭。DefaultServlet 設定 readmeFile、cachingAllowed。PreparedStatement 重用執行計劃。SELECT *,僅查所需欄位。LIMIT、Oracle ROWNUM、SQL Server OFFSET FETCH),避免全量載入內存。