Skip to content

八、集成web环境

一、基本三层架构环境

三层详情

Spring的基本三层架构环境清晰分为以下三层:

  1. 表示层(或Web层)web层
    • 主要负责处理用户的请求和响应。
    • 与用户直接交互,通常由Controllers组成,用于接收输入并调用下层的服务来处理业务逻辑。
    • 在Spring MVC中,这一层包含View(视图)、Controller(控制器)和相关的技术栈(如JSP、HTML、CSS、JavaScript等)。
    • 表示层的作用是接收用户的请求,并委派给不同的业务逻辑处理,然后展示请求的处理结果。
  2. 业务逻辑层(或服务层)service层
    • 也称为服务层,是应用程序的核心所在。
    • 负责具体的业务操作,如事务管理、业务逻辑编排等。
    • 在Spring中,业务逻辑层通常由Service接口和相应的实现类组成,例如StudentServiceOrderService等。
    • 这一层对上提供接口,并包含接口的实现,处理从表示层传递过来的请求,并可能调用数据访问层来获取或存储数据。
  3. 数据访问层(或持久层)dao层
    • 主要与数据库进行交互,执行CRUD(创建、读取、更新、删除)操作。
    • 是业务逻辑层和数据库之间的桥梁。
    • 在Spring中,数据访问层通常使用DAO(Data Access Object)模式,例如StudentDaoOrderDao等。
    • 数据访问层的作用是完成相关数据的提取、写入、修改、删除等操作,为业务逻辑层提供数据支持。

1、依赖准备

xml
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>6.1.6</version>
</dependency>
xml
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
xml
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>

2、插件准备

tomcat

xml
<build>
    <finalName>spring-mvc</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <server>tomcat9</server>
                <update>true</update>
                <port>8080</port>
                <path>/</path>
            </configuration>
        </plugin>
    </plugins>
</build>

3、三层

dao层

java
public interface UserDao {
    public void save();
}
java
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("用户保存中...");
    }
}

service层

java
public interface UserService {
    public void save();
}
java
public class UserServiceImpl implements UserService {

    private UserDao userDao;

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

    public void save() {
        userDao.save();
    }
}
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">

    <bean id="userDao" class="com.hdq.dao.impl.UserDaoImpl"></bean>
    <bean id="userService" class="com.hdq.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>
</beans>

web层

java
@WebServlet("/userService")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    }
}

4、运行

  1. 访问本地8080端口的\userService路由
  2. 控制台打印用户保存中...证明成功了

二、自定义ApplicationContext应用上下文监听器

介绍

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

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

1、创建ContextLoaderListener

java
@WebListener
public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
         ServletContext servletContext = servletContextEvent.getServletContext();    
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); 
		servletContext.setAttribute("app", app); 
		System.out.println("Spring容器创建完毕...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
java
@WebListener
public class ContextLoaderListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
         ServletContext servletContext = servletContextEvent.getServletContext();
		String contextConfigLocation= servletContext.getInitParameter("contextConfigLocation");
		ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
		servletContext.setAttribute("app", app);
		System.out.println("Spring容器创建完毕...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

2、使用

java
@WebServlet("/userService")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();	
        ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app"); 
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    }
}
java
//ContextLoaderUtil工具类
public class WebContextLoaderUtils {
    public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
        return (ApplicationContext) servletContext.getAttribute("app");
    }
}

@WebServlet("/userService")
public class UserServlet extends HttpServlet {

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

三、Spring的ApplicationContext应用上下文监听器因jdk版本,尚未实现成功,但教程正确

1、导入Spring-web坐标

xml
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>6.1.6</version>
</dependency>

2、配置web.xml

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

3、使用WebApplicationContextLoader

请注意

由于jdk的升级,可能需要注意javax-servlet-api和jakarta-servlet-api

java
@WebServlet("/userService")
public class UserServlet extends HttpServlet {

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