Spring整合web环境

目录

Javaweb三大组件及环境特点

Spring整合web环境的思路及实现

Spring的web开发组件spring-web

MVC框架思想及其设计思路


Javaweb三大组件及环境特点

Spring整合web环境_第1张图片

 

Spring整合web环境的思路及实现

Spring整合web环境_第2张图片

 Spring整合web环境_第3张图片

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的坐标

    
      org.springframework
      spring-web
      5.2.5.RELEASE
    



    
        org.springframework.web.context.ContextLoaderListener
    

 




    
        contextClass
        com.xfy.config.MyxfyApplicationContext
    
    
        org.springframework.web.context.ContextLoaderListener
    

 

MVC框架思想及其设计思路

Spring整合web环境_第4张图片

 Spring整合web环境_第5张图片

 Spring整合web环境_第6张图片

你可能感兴趣的:(java,spring)