• Spring学习笔记:spring整合web之spring-web架包的引用(WebApplicationContextUtils注入容器)


    WebApplicationContextUtils

    一、Spring整合web之前

      案例:给部门列表添加新部门

    import org.apache.log4j.Logger;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import javax.servlet.annotation.WebServlet;
    
    @WebServlet(name = "DeptServlet", urlPatterns = "/DeptServlet")
    public class DeptServlet extends javax.servlet.http.HttpServlet {
        private static Logger logger = Logger.getLogger(DeptServlet.class);
        @Override
        protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
            request.setCharacterEncoding("UTF-8");
            String action = request.getParameter("action");
            String deptname = request.getParameter("name");
            int id = Integer.parseInt(request.getParameter("id"));
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            IDeptService deptService = (IDeptService) context.getBean("deptService");
            Dept dept = new Dept();
            dept.setDeptname(deptname);
            int i = deptService.addDept(dept);
            logger.debug("执行"+i+"条数据!");
            logger.debug(action+"
    "+deptname+id);
            if (i>0){
                request.getRequestDispatcher("success.jsp").forward(request,response);
            }else{
                response.sendRedirect("index.jsp");
            }
        }
        @Override
        protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
            this.doPost(request, response);
        }
    }
    <html>
    <head>
        <base href="<%=basePath%>">
        <title>添加部门</title>
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta name="Content-Type" content="text/html; charset=utf-8"/>
        <%--<link rel="stylesheet" type="text/css" href="style.css">--%>
    </head>
    <body>
    <h2>添加部门</h2>
        <form action="/DeptServlet?action=add" method="post">
            部门:<input type="text" name="name"/>
            序号:<input type="number" name="id"/>
            <input type="submit" value="添加"/>
        </form>
    <h2>修改部门</h2>
    <form action="/empServlet?action=modify" method="post">
        部门:<input type="text" name="name"/>
        部门新名称:<input type="text" name="newname"/>
        <input type="submit" value="修改"/>
    </form>
    </body>
    </html>

    二、发现问题(资源浪费)

    tips:有什么办法可以只创建一次ApplicationContext对象吗?在这里可以使用监听器,在系统启动时创建一个ApplicationContext对象,

    之后servlet引用对象即可:::::

    三、使用监听器管理ApplicationContext对象(整合Spring)

      1.系统添加spring-web整合架包

    <!--Web整合-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>

      2.在web.xml文件中配置监听器

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      <!--Servlet共享applicationContext-->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
    
      <!--配置上下文监听器-->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    </web-app>

      3.Servlet方法中使用WebApplicationContextUtils创建ApplicationContext对象

    WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

      修改案例:

    import org.apache.log4j.Logger;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    import javax.servlet.annotation.WebServlet;
    
    @WebServlet(name = "DeptServlet", urlPatterns = "/DeptServlet")
    public class DeptServlet extends javax.servlet.http.HttpServlet {
        private static Logger logger = Logger.getLogger(DeptServlet.class);
        @Override
        protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
            request.setCharacterEncoding("UTF-8");
            String action = request.getParameter("action");
            String deptname = request.getParameter("name");
            int id = Integer.parseInt(request.getParameter("id"));
            //ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
            IDeptService deptService = (IDeptService) context.getBean("deptService");
            Dept dept = new Dept();
            dept.setDeptname(deptname);
            int i = deptService.addDept(dept);
            logger.debug("执行"+i+"条数据!");
            logger.debug(action+"
    "+deptname+id);
            if (i>0){
                request.getRequestDispatcher("success.jsp").forward(request,response);
            }else{
                response.sendRedirect("index.jsp");
            }
        }
        @Override
        protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
            this.doPost(request, response);
        }
    }

      使用框架编写程序,也是一个资源整合和优化的过程。

  • 相关阅读:
    最实用的深度学习教程 Practical Deep Learning For Coders (Kaggle 冠军 Jeremy Howard 亲授)
    线性代数的本质与几何意义 01. 向量是什么?(3blue1brown 咪博士 图文注解版)
    【小蜜蜂老师主讲】基于STM32CubeMX的嵌入式开发基础教程
    【STM32专题教程】STM32CubeMX的安装与快速入门
    【技能大赛真题】2019年物联网国赛任务三题1-无线通信系统
    【CC2530强化实训03】定时器间隔定时实现按键长按与短按
    【CC2530强化实训04】定时器间隔定时实现按键N连击
    【CC2530强化实训02】普通延时函数实现按键的长按与短按
    【CC2530强化实训01】普通延时函数实现按键的长按与短按
    【蓝桥杯单片机12】实时时钟DS1302的基本操作
  • 原文地址:https://www.cnblogs.com/tengqiuyu/p/7723977.html
Copyright © 2020-2023  润新知