在JSP中使用Spring其實很容易,主要用到Spring的WebApplicationContextUtils.getWebApplicationContext函數。
要再JSP里面得到ApplicationContext需要這么做,首先import="org.springframework.web.context.support.*,org.springframework.context.*"
然后可以通過如何做法:
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
這樣就得到了ApplicationContext,就可以操作Spring了。
JSP本來就可以認為是一個Servlet,所以使用getServletContext()就是理所應當了。
一:web.xml配置
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
二:在JSP
<%@ page import="org.springframework.context.ApplicationContext"%>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@ page import="com.yourcompany.service.CategoryService"%>
<%
//上面的CategoryService引用是我自己的東西
//applicationContext.xml中一定要有完整的依賴鏈,從dataSource到CategoryService
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
CategoryService cs = (CategoryService) ctx.getBean("CategoryService");
List list =cs.getCategoryDAO().findAll();
%>