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

相关推荐
Kagol1 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
GIS之路2 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide2 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
桦说编程2 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
ssshooter2 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
格砸3 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
Live000004 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉4 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化