◆ Spring整合web环境
- Javaweb三大组件及环境特点
- Spring整合web环境的思路及实现
把ApplicationContext放在ServleContent域【listen组件中】中
ContextLoaderListener :部分代码写死了
/**
* 配置通用的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:减少写死代码
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
ApplicationContext applicationContext = (ApplicationContext) servletContext.getAttribute("applicationContext.xml");
return applicationContext;
}
}
- Spring的web开发组件spring-web
使用xml注解
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.7</version>
</dependency>
<?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>
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框架思想与设计思路