14.Spring与Web环境集成

如果你是一路从本章节学过来的话,想来这一章很好理解。

 

一、手动创建监听器

逻辑:

(1)设置一个监听器监。当Spring容器创建的时候,就加载配置文件。

(2)只不过这边对配置文件做了处理,通过web.xml里的<context-parm>把配置文件的名称放进去,这样就做了解耦。因此加载的代码其实是写死的,要变的话只需要改变web.xml里的配置文件参数就行(妙啊)

(3)对传统的 ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");代码做了改造。

*1)因为按照这个写法,每有一个Controller就会创建一个Spring容器,这很不合理。

*2)因此在监听器里一旦监听到服务启动,就创建Spring容器,然后把这个Spring容器放到Context域里,这样整个项目就只有一个Spring容器。

*3)然后每个Controller在调用容器的时候,写一个专门调用容器的方法(类似于工厂),每个Controller调用那个方法即可引用Spring容器

 

目录

coding-14.Spring与Web环境集成-

UserDao

package com.xupeng.dao;

public interface UserDao {
    public void save();
}

UserDaoImpl

package com.xupeng.dao.impl;

import com.xupeng.dao.UserDao;

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("save running...");
    }
}

UserService

package com.xupeng.service;

public interface UserService {
    public void save();
}

UserServiceImpl

package com.xupeng.service.impl;

import com.xupeng.dao.UserDao;
import com.xupeng.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void save() {
        userDao.save();
    }
}

WebApplicationContextUtils

package com.xupeng.listener;

import org.springframework.context.ApplicationContext;

import javax.servlet.ServletContext;

public class WebApplicationContextUtils {
    public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
        return (ApplicationContext)servletContext.getAttribute("app");
    }
}

UserServlet

package com.xupeng.web;

import com.xupeng.listener.WebApplicationContextUtils;
import com.xupeng.service.UserService;
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;

public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    }

}

ContextLoaderListener

package com.xupeng.listener;

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

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

public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        //读取web.xml中的全局参数
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        //将spring的应用上下文对象存储到servletContext域中
        servletContext.setAttribute("app",app);
        System.out.println("spring创建成功");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>


    <bean id="userDao" class="com.xupeng.dao.impl.UserDaoImpl"></bean>

    <bean id="userService" class="com.xupeng.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

</beans>

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xupeng?serverTimezone=UTC
jdbc.username=root
jdbc.password=root

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

    <!--配置监听器-->
    <listener>
        <listener-class>com.xupeng.listener.ContextLoaderListener</listener-class>
    </listener>

    <!--全局初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>applicationContext.xml</param-value>
    </context-param>
    
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.xupeng.web.UserServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
    </servlet-mapping>
</web-app>

结果:

coding-14.Spring与Web环境集成-

 

二、SpringMvc里面的ContextLoadListener

上述是我们自己手动做的,其实Spring已经帮我们封装好了。我们只需要做以下两个步骤即可完成上述功能:

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

(2)使用WebApplicationContextUtils获取应用上下文对象ApplicationContext

 

具体代码基本与上述相同,需要修改的如下:

pom.xml:添加以下依赖

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>

web.xml:<listener>和<context-parm>参数

<?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">

    <!--配置监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--全局初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.xupeng.web.UserServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
    </servlet-mapping>
</web-app>

UserServlet:不要引用自己的,引用Spring的

package com.xupeng.web;

import com.xupeng.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

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;

public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
//        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    }

}

 

匿名

发表评论

匿名网友