• 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);
      }
    }
  • 相关阅读:
    HDU_1068_Girls and Boys_二分图匹配
    Bringing Native Performance to Electron
    BIM开发引挈
    旷视科技 -- Face++ 世界最大的人脸识别技术平台
    freedownloadmanager 下载工具,代替 讯雷
    两种 AuthorizationSchemes 在 ASP.NET Core 2
    layout 的应用
    递归获取一个树层次结构(合同清单)的部分选择项(计量合同清单),以及递归删除部分清单
    Nest + typeorm
    http://nancyfx.org + ASPNETCORE
  • 原文地址:https://www.cnblogs.com/fengmingyue/p/6202892.html
Copyright © 2020-2023  润新知