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

相关推荐
三门5 分钟前
docker安装mysql8.0.20过程
前端
加什么瓦16 分钟前
SpringCloud——微服务
spring·spring cloud·微服务
南极Ou22 分钟前
Mybatis逆向工程详解(附源码文件)动态创建实体类、条件扩展类、Mapper接口、Mapper.xml映射文件
xml·java·mybatis
Moshow郑锴28 分钟前
IDEA为何一直无法使用超过4g内存
java·ide·intellij-idea
木头左29 分钟前
Docker容器化镜像分层原理及优化策略
java·eureka
李少兄30 分钟前
IntelliJ IDEA代码提示忽略大小写设置详解
java·ide·intellij-idea
BillKu41 分钟前
Vue3 + Vite 中使用 Lodash-es 的防抖 debounce 详解
前端·javascript·vue.js
一只小风华~1 小时前
HTML前端开发:JavaScript的条分支语句if,Switch
前端·javascript·html5
橙子家1 小时前
Select 组件实现【全选】(基于 Element)
前端
超级土豆粉1 小时前
HTML 语义化
前端·html