spring整合web

0 导入jar包

1488305-20190813204038274-1355370670.jpg

1 tomcat启动加载配置文件

servlet-->init(ServletConfig)-->2
filter-->init(FilterConfig)-->web.xml 注册过滤器自动调用
listener-->ServletContextListner-->servletContext对象监听
spring提供监听器 ContextLoaderListener -->web.xml ...
    如果只配置监听器,默认加载xml位置:/WEB-INF/applicationContext.xml

2 确定配置文件位置,通过系统初始化参数

ServletContext初始化参数 web.xml


    contextConfigLocation
    classpath:applicationContext.xml

xml配置文件



 
 
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
  
  
    org.springframework.web.context.ContextLoaderListener
  

3从ServletContext作用域 获得spring容器(了解)

package com.itheima.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itheima.service.AccountService;

/**
 * Servlet implementation class HellowServlet
 */
@WebServlet("/HellowServlet")
public class HellowServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public HellowServlet() {
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //从applicationContext作用于(ServletContext)获得spring容器
        //方式1:手动从作用域获取
        ApplicationContext applicationContext=
            (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        //方式2通过工具获取
        ApplicationContext applicationContext2=
                WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //操作
        AccountService accountService= (AccountService)applicationContext.getBean("accountService",AccountService.class);
        accountService.transfer("jack", "rose", 1000);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

转载于:https://www.cnblogs.com/a1737301376/p/11348414.html

你可能感兴趣的:(spring整合web)