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+"\n"+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+"\n"+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);
    }
}

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

posted @ 2017-10-24 15:50  滕秋宇  阅读(1446)  评论(0编辑  收藏  举报