JSP 本質是 Servlet,可通過 WebApplicationContextUtils 獲取 Spring 容器上下文,進而訪問 Bean。
<%@ page import="org.springframework.web.context.support.*,org.springframework.context.*" %>ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());MyBean bean = (MyBean) ctx.getBean("beanId");<%@ page import="org.springframework.web.context.support.*,org.springframework.context.*" %>
<%
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
MyService service = (MyService) ctx.getBean("myService");
String result = service.doSomething();
%>
<html><body>Result: <%= result %></body></html>
原理:getServletContext() 來自 JSP 隱含對象 application,Spring 在啟動時將 WebApplicationContext 綁定在 ServletContext 屬性中,工具類負責查找並返回。