目录
Javaweb三大组件及环境特点
Spring整合web环境的思路及实现
Spring的web开发组件spring-web
MVC框架思想及其设计思路
Javaweb三大组件及环境特点
Spring整合web环境的思路及实现
package com.xfy.listener;
import com.xfy.config.SpringConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListenter implements ServletContextListener {
private String CONTEXT_CONFIG_LOCATION="ContextConfigLocation";
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
String initParameter = servletContext.getInitParameter(CONTEXT_CONFIG_LOCATION);
// initParameter=initParameter.substring("classpath".length());
//1.创建Spring容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(initParameter);
//2.将容器存入ServletContext中
servletContext.setAttribute("applicationContext",applicationContext);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
public class WebAppLicationContext {
public static ApplicationContext getWebAppLicationContext(ServletContext servletContext){
ApplicationContext applicationContext = (ApplicationContext) servletContext.getAttribute("applicationContext");
return applicationContext;
}
}
@WebServlet(urlPatterns = "/accountServlet")
public class AccountServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ApplicationContext applicationContext = WebAppLicationContext.getWebAppLicationContext(request.getServletContext());
AcountService bean = applicationContext.getBean(AcountService.class);
bean.transforMoney("tom","lucy",500);
}
Spring的web开发组件spring-web
Spring其实已经为我们定义好了一个ContextLoaderListener,使用方式跟我们上面自己定义的大体一样
先导入Spring-web的坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<!-- 定义全局参数 -->
<context-param>
<param-name>contextClass</param-name>
<param-value>com.xfy.config.MyxfyApplicationContext</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
MVC框架思想及其设计思路