Spring快速入门——Spring集成Web环境

本文介绍了如何在Web环境中搭建Spring的三层架构,包括pom.xml配置、applicationContext.xml配置、各层代码实现以及web.xml配置。此外,讨论了通过ServletContextListener监听器和WebApplicationContextUtils工具类优化应用上下文的获取,避免重复加载配置文件。最后,提到了Spring提供的ContextLoaderListener监听器简化配置和获取应用上下文的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本三层架构环境搭建
  • pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>spring_mvc</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.3.16</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.3.16</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.17</version>
            </dependency>
            <dependency>
                <groupId>c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.1.2</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.8</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.1</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>javax.servlet.jsp-api</artifactId>
                <version>2.3.3</version>
            </dependency>
        </dependencies>
    </project>
    
  • applicationContext.xml配置文件

    <?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">
    
        <!--配置Dao-->
        <bean id="userDao" class="com.study.dao.impl.UserDaoImpl"/>
        <!--配置Service-->
        <bean id="userService" class="com.study.service.impl.UserServiceImpl">
            <property name="userDao" ref="userDao"/>
        </bean>
    </beans>
    
  • dao层

    package com.study.dao;
    
    public interface UserDao {
        public void save();
    }
    
    package com.study.dao.impl;
    
    import com.study.dao.UserDao;
    
    /**
     * @title: UserDaoImpl
     * @Author Mj
     * @Date: 2022/3/2 14:09
     * @Version 1.0
     */
    
    public class UserDaoImpl implements UserDao {
        public void save() {
            System.out.println("userDao save running...");
        }
    }
    
  • service层

    package com.study.service;
    
    public interface UserService {
        public void save();
    }
    
    package com.study.service.impl;
    
    import com.study.dao.UserDao;
    import com.study.service.UserService;
    
    /**
     * @title: UserServiceImpl
     * @Author Mj
     * @Date: 2022/3/2 14:12
     * @Version 1.0
     */
    
    public class UserServiceImpl implements UserService {
    
        private UserDao userDao;
    
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        public void save() {
            userDao.save();
        }
    }
    
  • web层

    package com.study.web;
    
    import com.study.service.UserService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * @title: UserServlet
     * @Author Mj
     * @Date: 2022/3/2 22:08
     * @Version 1.0
     */
    public class UserServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //加载配置文件,创建Spring容器
            ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = app.getBean(UserService.class);
            userService.save();
        }
    }
    
  • web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>UserServlet</servlet-name>
            <servlet-class>com.study.web.UserServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>UserServlet</servlet-name>
            <url-pattern>/userServlet</url-pattern>
        </servlet-mapping>
    </web-app>
    

部署在Tomcat服务器运行,访问localhost:8080/userServlet

image-20220302232131068

ApplicationContext应用上下文获取方式
  • 应用上下文对象是new ClassPathXmlApplicationContext(spring配置文件)方式获取的,但是每次从容器中获得Bean时都要编写new ClassPathXMLApplicationContext(spring配置文件),这样的弊端是配置文件加载多次,应用上下文对象创建多次

  • Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,再将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了

    • web.xml文件中添加以下配置

      <!--全局初始化参数-->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>applicationContext.xml</param-value>
      </context-param>
      <!--配置监听器-->
      <listener>
          <listener-class>com.study.listener.ContextLoaderListener</listener-class>
      </listener>
      
    • 在ContextLoaderListener.java监听Web应用的启动

      package com.study.listener;
      
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      
      import javax.servlet.ServletContext;
      import javax.servlet.ServletContextEvent;
      import javax.servlet.ServletContextListener;
      
      /**
       * @title: ContextLoaderListener
       * @Author Mj
       * @Date: 2022/3/2 23:28
       * @Version 1.0
       */
      public class ContextLoaderListener implements ServletContextListener {
          public void contextInitialized(ServletContextEvent sce) {
              //获取servletContext对象
              ServletContext servletContext = sce.getServletContext();
      
              //通过配置文件的方式创建容器
              // ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
      
              //将配置文件放到web.xml中,从读取web.xml中的全局参数
              String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
              ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
      
              //将Spring的应用上下文对象存储到ServletContext域中
              servletContext.setAttribute("app",app);
      
              System.err.println("spring容器创建完毕...");
              System.err.println("监听器执行完毕...");
          }
      
          public void contextDestroyed(ServletContextEvent sce) {
      
          }
      }
      
    • 编写工具类WebApplicationContextUtils类,返回从servletContext域获取的应用上下文ApplicationContext对象

      package com.study.utils;
      
      import org.springframework.context.ApplicationContext;
      
      import javax.servlet.ServletContext;
      
      /**
       * @title: WebApplicationContextUtils
       * @Author Mj
       * @Date: 2022/3/2 23:45
       * @Version 1.0
       */
      public class WebApplicationContextUtils {
          public static ApplicationContext getApplicationContext(ServletContext servletContext){
               return (ApplicationContext) servletContext.getAttribute("app");
          }
      }
      
    • 在UserServlet.java中通过WebApplicationContextUtils类的getApplicationContext()方法获取应用上下文ApplicationContext对象

      package com.study.web;
      
      import com.study.service.UserService;
      import com.study.utils.WebApplicationContextUtils;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      
      import javax.servlet.ServletContext;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      
      /**
       * @title: UserServlet
       * @Author Mj
       * @Date: 2022/3/2 22:08
       * @Version 1.0
       */
      public class UserServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              //加载配置文件,创建Spring容器
              // ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
      
              ServletContext servletContext = req.getServletContext();
      
              // ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
              ApplicationContext app = WebApplicationContextUtils.getApplicationContext(servletContext);
              UserService userService = app.getBean(UserService.class);
              userService.save();
          }
      }
      
Spring提供获取应用上下文的工具

上面的分析不用手动实现,Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象

所以我们只需要做两件事:

  1. 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)

    <!--pom.xml中先导入坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.3.16</version>
    </dependency>
    
    <!--在web.xml中配置监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
  2. 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

    WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    
知识要点总结
Spring集成Web环境步骤
  1. 配置ContextLoaderListener监听器
  2. 使用WebApplicationContextUtils获得应用上下文
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值