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

相关推荐
打小就很皮...9 分钟前
React 19 + Vite 6 + SWC 构建优化实践
前端·react.js·vite·swc
Highcharts.js12 分钟前
使用Highcharts与React集成 官网文档使用说明
前端·react.js·前端框架·react·highcharts·官方文档
这是个栗子12 分钟前
AI辅助编程(二) - 通译千问
前端·ai·通译千问
VT.馒头23 分钟前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
思想在飞肢体在追25 分钟前
Springboot项目配置Nacos
java·spring boot·后端·nacos
cyforkk27 分钟前
09、Java 基础硬核复习:异常处理(容错机制)的核心逻辑与面试考点
java·数据库·面试
??(lxy)1 小时前
java高性能无锁队列——MpscLinkedQueue
java·开发语言
数研小生1 小时前
Full Analysis of Taobao Item Detail API taobao.item.get
java·服务器·前端
Shirley~~1 小时前
Vue-skills的中文文档
前端·人工智能
毎天要喝八杯水1 小时前
搭建vue前端后端环境
前端·javascript·vue.js