正常整合Servlet和Spring沒有問題的
public class UserServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService = (UserService) applicationContext.getBean("userService");userService.sayHello();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);} }
但是每次執行Servlet的時候都要加載Spring配置,加載Spring環境,極大地降低效率!!!
解決辦法
1:在Servlet的init方法中加載Spring配置文件?(不好)
當前這個Servlet可以使用,但是其他的Servlet用不了了!!!如果要使用,必須每個Servlet的init方法中都要加載Spring配置文件,太麻煩(pass)
2:將加載的信息內容放到ServletContext中(正確)
ServletContext對象是全局的對象.服務器啟動的時候創建的.在創建ServletContext的時候就加載Spring的環境,ServletContextListener用于監聽ServletContext對象的創建和銷毀
使用方法
1:導入Spring web開發jar包:spring-web-3.2.0.RELEASE.jar
2:將Spring容器初始化,交由web容器負責,配置核心監聽器 ContextLoaderListener,配置全局參數contextConfigLocation(用于指定Spring的框架的配置文件位置)
在web.xml中配置
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value> </context-param>
修改程序的代碼
public class UserServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/*也可用這種方式獲得applicationContext:WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);*/WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());UserService userService = (UserService) applicationContext.getBean("userService");userService.sayHello();}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }