spring基础知识 (28):spring在web中的应用的基本思路

spring在web应用中的配置与使用的基本思路:

  • 需要额外加入的 jar 包:
    spring-web-4.0.0.RELEASE.jar
    spring-webmvc-4.0.0.RELEASE.jar
  • Spring 的配置文件在java应用中一样配置
  • 如何创建 IOC 容器 ?
    在非WEB应用中,使用ApplicationContext接口直接创建
    在WEB应用中,应该在应用启动时就创建:
    • 首先创建一个监听器: 使用ServletContextListener 接口
    • 在contextInitialized(ServletContextEvent sce) 方法中创建 IOC 容器.
    • 为了保证在 WEB 应用的其他组件中能够访问 IOC 容器。需要将创建的IOC容器放入application域中。
    • 然后在web.xml中配置这个监听器,这样在应用启动时就可以执行这个监听器,然后在application域中创建IOC容器。
    • 在application域中获取IOC容器并使用。

模拟测试

  • 测试实体:Person
package com.spring.domain;

public class Person {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + "]";
    }

}
  • 配置文件中配置该Bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.spring.domain.Person">
        <property name="name" value="小明"></property>
    </bean>

</beans>
  • 使用ServletContextListener 接口创建监听器:
package com.spring.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Application Lifecycle Listener implementation class SpringServletContextListener
 *
 */
@WebListener
public class SpringServletContextListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public SpringServletContextListener() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0) {
        //servlet容器
        ServletContext servletContext = arg0.getServletContext();
        /*
         * 获取在web.xml中配置的spring配置文件的信息
         *  <context-param>
         *      <param-name>configLocation</param-name>
         *      <param-value>classpath:applicationContext.xml</param-value>
         *  </context-param>
         */
        String config  = servletContext.getInitParameter("configLocation");
        //初始化IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        //将IOC容器放到application域中,因此在servlet中就能使用IOC容器
        servletContext.setAttribute("ApplicationContext", ctx);
    }

    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }

}

  • 在web.xml中注册这个监听器
<!-- 这里配置spring配置文件信息,在监听器中在application域中可获取 -->
<context-param>
    <param-name>configLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>com.spring.listener.SpringServletContextListener</listener-class>
</listener>
  • 测试:在Servlet使用IOC容器
package com.spring.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.spring.domain.Person;

/**
 * Servlet implementation class PersonServlet
 */
@WebServlet("/personServlet")
public class PersonServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从域中得到ApplicationContext(IOC容器)
        ServletContext servletContext = getServletContext();
        ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
        Person person = (Person) ctx.getBean("person");
        System.out.println(person);
    }
}

通过前台jsp页面访问这个servlet:

<a href="personServlet">personServlet</a>

这里写图片描述


spring自带的Listener

上面其中一个步骤是使用ServletContextListener 接口创建IOC容器,其实spring已经帮我们实现这个接口,并创建IOC容器,我们可以直接使用。

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

在这种情况下,我们就不用自己去写SpringServletContextListener implements ServletContextListener
如果要在servlet中使用IOC容器,使用工具类:
WebApplicationContextUtils

package com.spring.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.spring.beans.Person;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
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 {
        ServletContext servletContext = getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
        Person person = (Person) ctx.getBean("person");
        System.out.println(person);
    }

}

总结:在web项目中使用spring

  • 在web.xml中配置Listener
  • 配置spring配置文件
  • 如果需要获取IOC容器,可以用WebApplicationContextUtils,不过一般情况下我们是不需要获取IOC容器。一般情况下,我们可以使用spring的注入获取bean.但是在这里测试使用的是servlet,不能使用注入的方式。因为servlet和applicationContext是两个平级的概念。所以servlet只能够通过tomcat中的api来获取applicationContext对象。

猜你喜欢

转载自blog.csdn.net/abc997995674/article/details/80335132