在傳統 JSP 頁面(非 Spring MVC View Resolver 渲染)中,需手動從 Spring 容器取得 Bean 實例(如 Service、DAO、工具類)進行業務邏輯處理。
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%
// 1. 取得 ServletContext
ServletContext sc = this.getServletConfig().getServletContext();
// 2. 從 ServletContext 獲取 WebApplicationContext
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
// 3. 根據 Bean ID 取得目標 Bean
MyService myService = (MyService) ac.getBean("myServiceBeanId");
// 4. 呼叫業務方法
List<Data> list = myService.queryAll();
%>
ServletContext 獲取 WebApplicationContext(Spring 容器的 Web 專用子介面)。ServletContext 屬性 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。web.xml 已配置 ContextLoaderListener,啟動時初始化 Spring 容器並綁定至 ServletContext。// com.utils.SpringContextHolder.java
public class SpringContextHolder {
private static ApplicationContext context;
public static void setApplicationContext(ApplicationContext ac) {
context = ac;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) context.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
}
// 在 Spring 配置中註冊(實作 ApplicationContextAware)
@Component
public class SpringContextInitializer implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext ac) {
SpringContextHolder.setApplicationContext(ac);
}
}
<%@ page import="com.utils.SpringContextHolder" %>
<%
MyService service = SpringContextHolder.getBean("myServiceBeanId");
// 或直接按類型獲取(單例 Bean)
MyService service2 = SpringContextHolder.getBean(MyService.class);
%>
getBean 為單例查找,效能極高,但頻繁在 JSP 呼叫仍建議快取至頁面變數。getBean(Class<T>) 避免轉型錯誤。Spring MVC 專案中,Controller 將資料放入 Model,View(JSP/Thymeleaf)直接透過 EL ${model.data} 存取,完全不需在 JSP 手動取 Bean。建議逐步遷移至 Spring MVC 架構。