JSP/Servlet 應用效能優化是一門系統工程。本文精選七大高收益優化手段,涵蓋緩存、容器配置、會話管理、傳輸壓縮、線程模型、包含機制、Bean 作用域,並附贈字串處理與日誌輸出微優化。
init() 僅在 Servlet 實例化時執行一次,適合放置昂貴的一次性操作:
DataSource(JNDI 查詢極其耗時)public class ControllerServlet extends HttpServlet {
private DataSource dataSource;
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/myDS"); // 僅查詢一次 JNDI
} catch (NamingException e) { throw new ServletException(e); }
}
public DataSource getDataSource() { return dataSource; }
}
開發時 auto-reload 方便修改即生效,但生產環境會導致 ClassLoader 頻繁掃描、重新編譯,嚴重拖垮效能。
conf/web.xml 中 JspServlet 的 development 設為 false;Context 的 reloadable="false"。Session 序列化/反序列化、記憶體佔用、集群同步皆是成本。
| 優化手段 | 說明 |
|---|---|
| 頁面指令關閉 | <%@ page session="false" %> 禁用無需 Session 的頁面(靜態頁、API 端點) |
| 避免存大物件 | Session 放大量資料會觸發頻繁序列化,改用 Redis/資料庫 + Session 只存 Key |
| 及時銷毀 | 流程結束呼叫 session.invalidate() |
| 縮短逾時 | web.xml <session-timeout>15</session-timeout>(單位:分鐘),平衡體驗與資源 |
HTML/CSS/JS 文字資源壓縮率常超過 70%,大幅降低頻寬與載入時間。
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String acceptEncoding = req.getHeader("Accept-Encoding");
OutputStream out;
if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
resp.setHeader("Content-Encoding", "gzip");
out = new GZIPOutputStream(resp.getOutputStream());
} else {
out = resp.getOutputStream();
}
// 寫入內容...
out.close();
}
生產環境建議直接在 **Nginx/Apache 反向代理層** 開啟 gzip on;,卸載應用伺服器 CPU。
預設「每請求一線程」模式在高併發下創建/銷毀線程開銷巨大。
server.xml <Executor> 定義共享線程池,<Connector executor="tomcatThreadPool"> 引用。minSpareThreads(啟動預熱)、maxThreads(上限)、maxIdleTime。| 機制 | 語法 | 編譯期/執行期 | 效能 | 適用 |
|---|---|---|---|---|
| 靜態包含 | <%@ include file="..." %> | 編譯期合併 | **最高**(單一 Servlet,無額外請求) | 通用頁首尾、工具片段 |
| 動態包含 | <jsp:include page="..." flush="true"/> | 執行期 RequestDispatcher.include() | 較低(獨立編譯、獨立 request/response) | 動態決定、需隔離變數作用域 |
**原則:能用靜態包含就不用動態包含。**
<jsp:useBean id="user" class="com.example.User" scope="request|session|application" />
page(預設):僅當前頁面請求有效,最輕量。request:轉發鏈共享,適合 Controller → View 傳遞。session:跨請求用戶級共享,**濫用會撐爆記憶體**。application:全應用單例,適合配置、快取,需自行同步。**錯誤範例**:一次性查詢 Bean 設為 session,導致用戶關閉瀏覽器前記憶體不釋放。
StringBuilder(非執行緒安全、效能高)或 StringBuffer(舊版線程安全),避免 + 產生大量臨時 String 物件。效能優化無銀彈,但上述七大策略覆蓋了 80% 的常見瓶頸。建議:先測量(Profiling/JMeter),再針對熱點優化,最後驗證效果,切忌盲目調優。