正常整合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);
}
}