核心程式碼
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%
ServletContext sc = this.getServletConfig().getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
// 獲取 Bean (需對應 Spring 配置檔中的 id)
YourServiceBean service = (YourServiceBean) ac.getBean("spring配置檔中的bean id");
// 使用服務
service.doSomething();
%>
關鍵步驟解析
- 取得
ServletContext:this.getServletConfig().getServletContext()
- 透過工具類獲取 Spring
ApplicationContext:WebApplicationContextUtils.getWebApplicationContext(sc)
- 呼叫
getBean("beanId") 取得實例,需強制轉型
前置條件
- 專案已整合 Spring Framework
web.xml 配置 ContextLoaderListener 載入 Spring 配置檔
- 目標 Bean 已在 Spring 配置檔中定義 (如
<bean id="userService" class="..."/>)
注意事項
| 項目 | 說明 |
| 效能 | 每次請求執行 JSP 程式碼片段,建議快取 ApplicationContext |
| 架構 | JSP 直接存取 Service 屬違反 MVC 分層,僅建議原型/舊專案維護使用 |
| 替代方案 | Controller 注入 Service → 放入 Model → JSP 透過 EL 存取 |
| Spring 版本 | Spring 3.0+ 皆支援此工具類用法 |
現代最佳實踐
<!-- Controller -->
@Controller
public class MyController {
@Autowired UserService userService;
@GetMapping("/page")
public String showPage(Model model) {
model.addAttribute("users", userService.findAll());
return "myPage"; // 對應 myPage.jsp
}
}
<!-- myPage.jsp -->
<c:forEach items="${users}" var="user">
${user.name} <br/>
</c:forEach>
原則: JSP 僅負責視圖渲染,業務邏輯與資料存取完全委派給 Controller 與 Service 層。
- 上一篇文章: JSP 倒數計時與自動跳轉頁面實作
- 下一篇文章: JSP 檔案如何開啟?編輯與執行環境完整指南
Copyright ©
程式碼之家 All Rights Reserved