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框架思想与设计思路

相关推荐
LinXunFeng5 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
乘风gg9 小时前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭10 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒10 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭10 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
小bo波10 小时前
从"任意文件复制"深挖Java I/O:字符流与字节流的本质抉择
java·nio·io流·后端开发·文件复制
Hyyy11 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin12 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
Pedantic12 小时前
本地通知(Local Notifications)学习笔记
前端
森蓝情丶12 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端