首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

在 JSP 中獲取 Spring ApplicationContext 實例

     編輯:關於JSP

JSP 本質是 Servlet,可通過 WebApplicationContextUtils 獲取 Spring 容器上下文,進而訪問 Bean。

實現步驟

  1. 頁面頂部導入包:<%@ page import="org.springframework.web.context.support.*,org.springframework.context.*" %>
  2. 獲取上下文:ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  3. 使用 Bean: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 屬性中,工具類負責查找並返回。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved