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

基本三层架构环境搭建

  • pom.xml

    
    <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.0modelVersion>
    
        <groupId>org.examplegroupId>
        <artifactId>spring_mvcartifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>warpackaging>
        <dependencies>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.3.16version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-testartifactId>
                <version>5.3.16version>
            dependency>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.17version>
            dependency>
            <dependency>
                <groupId>c3p0groupId>
                <artifactId>c3p0artifactId>
                <version>0.9.1.2version>
            dependency>
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>1.2.8version>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>javax.servlet-apiartifactId>
                <version>4.0.1version>
            dependency>
            <dependency>
                <groupId>javax.servlet.jspgroupId>
                <artifactId>javax.servlet.jsp-apiartifactId>
                <version>2.3.3version>
            dependency>
        dependencies>
    project>
    
  • applicationContext.xml配置文件

    
    <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="userDao" class="com.study.dao.impl.UserDaoImpl"/>
        
        <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

    
    <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>UserServletservlet-name>
            <servlet-class>com.study.web.UserServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>UserServletservlet-name>
            <url-pattern>/userServleturl-pattern>
        servlet-mapping>
    web-app>
    

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

Spring快速入门——Spring集成Web环境_第1张图片

ApplicationContext应用上下文获取方式

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

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

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

      
      <context-param>
          <param-name>contextConfigLocationparam-name>
          <param-value>applicationContext.xmlparam-value>
      context-param>
      
      <listener>
          <listener-class>com.study.listener.ContextLoaderListenerlistener-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坐标)

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>5.3.16version>
    dependency>
    
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
  2. 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

    WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    

知识要点总结

Spring集成Web环境步骤
  1. 配置ContextLoaderListener监听器
  2. 使用WebApplicationContextUtils获得应用上下文

你可能感兴趣的:(Spring,java,spring,intellij-idea)