既然说到web自然就有servlet:
public class UserServlet extends HttpServlet {
@SuppressWarnings("resource")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 这种整合没有问题也可以。但是有一个问题每一次请求都加载spring坏境。
* 每一次请求都加载配置文件这 样是不好的。性能大大的降低
* 也许有人会这样解决这个问题servlet不是有个init方法吗?
* 将spring运行坏境的加载在init方法中加载这样 就保证了只加载一次
* 确实是只加载了一次,但是也还存在一个问题,就是这个spring的运行坏境这些配置文件只有这个
* servlet能使用,其他是servlet不能使用。
*
*/
ClassPathXmlApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
UserService bean = (UserService) context.getBean("userService");
bean.sayHello();
/**
* 使用Spring提供的整合web来有两种方式
* 一般会使用下面的一种方式
*将spring的坏境放在ServletContext这样域中。这个域是全局的。
*每一个加载时随着tomcat启动而加载这样 * 就解决了前面的缺点
*但是如何才能将这个spring的坏境放入servletContext域中。
*这时我们需要在web.xml文件中配置一个监听 器listener,
*利用监听器去监听这个ServletContext这个域创建和销毁。
*但是还有一个问题.spring坏境默认会到WEB-INF目录下加载配置文件。
*然而你的配置文件在src下。 如何才能加载这个核心的配置文件
这时候就需要配置一个全局的初始化参数告诉spring到src下去加载这个配置文件
<!--监听器配置 -->
<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>
*/
/*WebApplicationContext
context=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService bean = (UserService) context.getBean("userService");
bean.sayHello();
*/
}
/**
* The doPost method of the servlet. <br>
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}