在WEB應用中使用Spring(就是創建IOC容器放在域對象裏面)
1. Spring 如何在 WEB 應用中使用 ?
1). 需要額外加入的 jar 包:
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
2). Spring 的配置文件, 沒有什麼不同
3). 實現思路:
創建一個監聽器實現ServletContextListener接口,
然後在contextInitialized(ServletContextEvent sce) 方法中創建 IOC 容器,並將其放入servletcontext域對象中.
通過servletcontext域對象取得IOC容器.
web.xml配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 啓動 IOC 容器的 ServletContextListener -->
<listener>
<listener-class>創建的監聽器的全類名</listener-class>
</listener>
public class SpringServletContextListener implements ServletContextListener { public SpringServletContextListener() { // TODO Auto-generated constructor stub } public void contextInitialized(ServletContextEvent arg0) { //1. 獲取 Spring 配置文件的名稱. ServletContext servletContext = arg0.getServletContext(); String config = servletContext.getInitParameter("configLocation"); //1. 創建 IOC 容器 ApplicationContext ctx = new ClassPathXmlApplicationContext(config); //2. 把 IOC 容器放在 ServletContext 的一個屬性中. servletContext.setAttribute("ApplicationContext", ctx); } public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub { } public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 從 application 域對象中得到 IOC 容器的引用 ServletContext servletContext = getServletContext(); ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext"); //2. 從 IOC 容器中得到需要的 bean Person person = ctx.getBean(Person.class); person.hello(); } }
使用Spring提供的監聽器(ContextLoaderListener)
<!-- 配置 Spring 配置文件的名稱和位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 啓動 IOC 容器的 ServletContextListener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> //1. 從 appication 域對象中得到 IOC 容器的實例 ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application); //2. 從 IOC 容器中得到 bean Person person = ctx.getBean(Person.class); //3. 使用 bean person.hello();
Spring 如何整合 Struts2
首先把Struts2加入進來(jar包和倆個配置文件)
在 Spring 的 IOC 容器中配置 Struts2 的 Action
注意: 在 IOC 容器中配置 Struts2 的 Action 時, 需要配置 scope 屬性, 其值必須爲 prototype
<bean id="personAction" class="com.atguigu.spring.struts2.actions.PersonAction" scope="prototype"> <property name="personService" ref="personService"></property> </bean>
3. 加入struts2-spring-plugin-2.3.15.3.jar .配置 Struts.xml: action 節點的 class 屬性需要指向 IOC 容器中該 bean 的 id
<action name="person-save" class="personAction"> <result>/success.jsp</result> </action>