MVC (Model-View-Controller) 實現 Web 系統職能分工:
RequestDispatcher 即可完美實現 MVC (Model 2)。request.setAttribute("key", bean) / session.setAttribute / application.setAttribute。request.getRequestDispatcher("/WEB-INF/view.jsp").forward(req, resp)。<jsp:useBean id="key" type="pkg.Bean" scope="request"/> + <jsp:getProperty name="key" property="field"/>。type 屬性而非 class,確保對象由 Servlet 創建。jsp:getProperty,禁用 jsp:setProperty。request (單次請求)、session (用戶會話)、application (全域共享)。MVC 模式通常使用 request 作用域。| 場景 | 範圍 | Servlet 代碼 | JSP useBean scope |
|---|---|---|---|
| 每次請求生成新隨機數 | Request | request.setAttribute("key", val); | scope="request" |
| 顯示用戶姓名 (登入後) | Session | session.setAttribute("key", val); | scope="session" |
| 顯示全站共享質數表 | Application | synchronized(this){ app.setAttribute("key", val); } | scope="application" |
問題:forward 對瀏覽器透明,瀏覽器以原 Servlet URL 為基準解析 JSP 中相對路徑 (CSS/JS/圖片/超連結),導致 404。
最簡方案:所有資源引用使用絕對路徑 (以 / 開頭):<link href="/css/style.css">、<a href="/app/page.jsp">。