依赖项
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!--jsp依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--为了使用监听器,加入依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
在Servlet中,每一次页面跳转都会创建一个spring容器,所以要把容器放到全局作用域ServletContext中
// 创建spring的容器对象
// 但是这样做,每一次页面跳转都会创建一个spring容器,所以要把容器放到全局作用域ServletContext中
// 使用监听器,当全局作用域被创建时,创建容器,放到ServletContext中
String config = "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
StudentService studentService = (StudentService)ac.getBean("studentService");
解决方法:使用监听器,当全局作用域被创建时,创建容器,放到ServletContext中
在web.xml文件中配置
<!--配置监听器ContextLoaderListener
监听器被创建对象后,会读取 /WEB-INF/applicationContext.xml
为什么要读取配置文件:在监听器中要创建ApplicationContext对象,需要加载配置文件
/WEB-INF/applicationContext.xml 就是监听器默认读取的spring配置文件路径
默认路径是在WEB-INF下,可以修改默认路径
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--classpath:默认是从resource目录下-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
servlet代码改为:
//这样就能获取到容器对象ac
WebApplicationContext ac = null;
String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
Object attr = getServletContext().getAttribute(key);
if(attr != null){
ac = (WebApplicationContext) attr;
}
或者使用框架方法,获取容器对象
ServletContext sc = getServletContext();
ac = WebApplicationContextUtils.getWebApplicationContext(sc);