在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>