ServletContext初始化时创建Spring容器
获取容器
package com.hk.ssh.servlets; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.context.WebApplicationContext; import com.hk.ssh.beans.Student; import com.hk.ssh.service.IStudentService; public class RegisterServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); String ageStr = request.getParameter("age"); Integer age = Integer.valueOf(ageStr); Student student = new Student(name,age); //1、创建Spring 容器(这种创建方式每来一次请求就会创建一个ApplicationContext) //ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); /** * 采用如下方式创建Spring容器,在ServletContext初始化是创建容器 * ServletContext只初始化一次,所以整个web运用都只会有一个Spring容器 */ ServletContext application = request.getSession().getServletContext(); WebApplicationContext ac = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); //2、从容器中获取Service对象 IStudentService service = (IStudentService) ac.getBean("studentService"); //3、调用Service的addStudent() service.addStudent(student); request.getRequestDispatcher("/welcome.jsp").forward(request, response); } }完整项目源码:http://pan.baidu.com/s/1slEY7JR