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.8新特性-Lambda表达式
    博客园自定义样式(去广告、公告栏加头像、按钮样式)
    java月考题JSD1908第二次月考(含答案和解析)
    Java面试题_第四阶段
    Java面试题_第三阶段(Spring、MVC、IOC、AOP、DI、MyBatis、SSM、struts2)
    Java面试题_第二阶段(Servlet、HTTP、Session、JSP、 Ajax、Filter、JDBC、Mysql、Spring)
    Java面试题_第一阶段(static、final、面向对象、多线程、集合、String、同步、接口、GC、JVM)
    Oracle排名函数(Rank)实例详解
  • 原文地址:https://www.cnblogs.com/fengmingyue/p/6202892.html
Copyright © 2011-2022 走看看