Spring Web

◆ Spring整合web环境

- Javaweb三大组件及环境特点

- Spring整合web环境的思路及实现

把ApplicationContext放在ServleContent域【listen组件中】中

ContextLoaderListener :部分代码写死了

java 复制代码
/**
 * 配置通用的Spring容器的创建,只需要创建一次就可以
 */
public class ContextLoaderListener implements ServletContextListener {
    public void contextDestroyed(ServletContextEvent sce) {
        //1.创建Spring容器
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("application.xml");
        //2.将容器存储到servletContent域中
        sce.getServletContext().setAttribute("applicationContext",app);
        
    }
}

WebApplicationContextUtils:减少写死代码

java 复制代码
public class WebApplicationContextUtils {
    public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
        ApplicationContext applicationContext = (ApplicationContext) servletContext.getAttribute("applicationContext.xml");
        return applicationContext;
    }
}

- Spring的web开发组件spring-web

使用xml注解

java 复制代码
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.7</version>
        </dependency>
java 复制代码
<?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_3_1.xsd"
         version="3.1">

    <!--定义全局参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--配置Listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
java 复制代码
public class AccountServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ServletContext servletContext = request.getServletContext();
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        AccountService accountService = app.getBean(AccountService.class);
        accountService.transferMoney("tom","lucy",500);

    }



}

使用注解

硬核讲解:

105-Spring整合web环境-扩展-核心配置类方式怎样配置_哔哩哔哩_bilibili

◆ web层MVC框架思想与设计思路

相关推荐
计算机魔术师8 小时前
新兴多智能体系统的模式与问题
前端
数智化管理手记8 小时前
海量数据如何沉淀有效数据资产?数据标准化治理方案如何搭建?
java·大数据·人工智能
cfm_29148 小时前
SpringAI + Ollama 本地大模型
java·开发语言·人工智能·语言模型
用户059540174469 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css
满栀5859 小时前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
鲸采云SRM采购管理系统9 小时前
采购管理系统哪家好?2026最新测评对比
java·服务器·数据库
一拳不是超人9 小时前
DeepSeek Harness 为什么敢说"一切皆插件"?拆透 Cordis 引擎的五大核心机制
前端·人工智能·agent
IT_陈寒10 小时前
Python的GIL让我多写了500行代码
前端·人工智能·后端
风骏时光牛马10 小时前
AI智能体能力调度微服务
前端
0x5310 小时前
Java网络编程(二)
java·服务器·网络