zoukankan      html  css  js  c++  java
  • Spring整合web开发

    正常整合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);
      }
    }
  • 相关阅读:
    JDK1.0-缓冲流
    笔试错误1
    JVM 垃圾收集(转)
    Trie树和后缀树(转,简化)
    海量数据处理(转,简化)
    Struts2 内核之我见(转) -(主要是拦截器链和过滤链介绍和源码及其设计模式)
    phpize增加php模块
    Ubuntu下SVN安装和配置
    Linux下SVN配置hook经验总结
    Kruakal 算法——练习总结
  • 原文地址:https://www.cnblogs.com/fengmingyue/p/6202892.html
Copyright © 2011-2022 走看看