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);
}
}

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

Spring学习笔记:spring整合web之spring-web架包的引用(WebApplicationContextUtils注入容器)的更多相关文章

  1. Spring学习笔记四 整合SSH

    三大框架架构(整合原理) 步骤1:导包 Hibernate包 1.Hibernate包,hibernate/lib/required 2.hibernate/lib/jpa | java persis ...

  2. Spring学习笔记(1)——初识Spring

    一.Spring是什么       通常说的Spring其实指的是Spring Framework,它是Spring下的一个子项目,Spring围绕Spring Framework这个核心项目开发了大 ...

  3. Spring学习笔记(二) 初探Spring

    版权声明 笔记出自<Spring 开发指南>一书. Spring 初探 前面我们简单介绍了 Spring 的基本组件和功能,现在我们来看一个简单示例: Person接口Person接口定义 ...

  4. Spring学习笔记之整合struts

    1.现有项目是通过 <action    path="/aaaaAction"                type="org.springframework.w ...

  5. Spring学习笔记之整合hibernate

    1.web.xml里边要配置好对应的springxml的路径 <context-param> <param-name>contextConfigLocation</par ...

  6. Spring 学习笔记之整合Hibernate

    Spring和Hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心SQ ...

  7. 【Spring学习笔记-1】Myeclipse下Spring环境搭建

    *.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...

  8. Spring 学习笔记(一):Spring 入门

    1 Spring简介 Spring是一个轻量级Java开发框架,最早由Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题,是一个分层的Java SE/EE ful ...

  9. Spring学习笔记之一----基于XML的Spring IOC配置

    1. 在spring配置文件中,如果对一个property进行直接赋值,可使用<value>元素,spring负责将值转化为property指定的类型:也可以直接在property元素上使 ...

  10. Java框架spring 学习笔记(九):Spring的bean管理(@Required、@Component、@Autowired、@Resource注解)

    注解:代码里面特殊的标记,使用注解可以完成相关功能 注解写法:@注解名称(属性名.属性值) @Required 用在set方法上,一旦用了这个注解,那么容器在初始化bean的时候必须要进行set,也就 ...

随机推荐

  1. Java中Arrays工具类

    以下是实现六种功能的方法: 1.比较两个数组值是否相等: 结果为true.false.(布尔型不能比较) int []a={10,20,30}; int []b={10,20,30}; int []c ...

  2. 常见的vue面试题

    001.v-show与v-if的区别v-show:操作的是元素的display属性 v-if:操作的是元素的创建和插入相比较而言v-show的性能要高 002.methods.computed.wat ...

  3. Elasticsearch5.4 删除type

    首先要说明的是现在的Elasticsearch已经不支持删除一个type了,所以使用delete命令想要尝试删除一个type的时候会出现如下错误,如果存在一个名为edemo的index和tets的ty ...

  4. $.ajax()——超时设置,增加 loading 提升体验

    前端发送Ajax请求到服务器,服务器返回数据这一过程,因原因不同耗时长短也有差别,且这段时间内页面显示空白.如何优化这段时间内的交互体验,以及长时间内服务器仍未返回数据这一问题,是我们开发中不容忽视的 ...

  5. python web开发学习笔记一:javascript基础

    一.认识js: 能进入到软件所实习是我的最大的收获,也是我的荣幸,我相信努力付出一定能够换回收获. 项目最先开始的是接触到web前端的一些内容,我们需要利用flask搭建应该有的框架.我有一些pyth ...

  6. mariadb(mysql)的安装

    1 使用官方源安装mariadb vim /etc/yum.repos.d/MariaDB.repo 添加repo仓库配置内容 [mariadb] name=MariaDB baseurl=http: ...

  7. 网络编程-echo服务器

    代码: #coding="utf-8" #name=echo服务器 from socket import * #1.创建套接字 udpSocket = socket(AF_INET ...

  8. CODEVS-1018单词接龙

    单词接龙 原题:传送门 解题思路: 此题是典型的深搜题目,首先确定递归变量,表示字母的数量,每当满足一定条件,就往下一层递归,否则回溯 判断由哪个单词开始(因为可能字母首位可能相同),再确定之后所连单 ...

  9. IT人生的价值和意义 感觉真的有了

     为了做新闻APP,我居然短短一个月利用业余时间做了: 一个通用新闻采集器. 一个新闻后台审核网站. 一个通用采集器下载网站. 一个新闻微网站. 一个新闻APP, 而且还给新闻微网站和新闻 APP练就 ...

  10. 执行Hive时出现org.apache.hadoop.util.RunJar.main(RunJar.java:136) Caused by: java.lang.NumberFormatException: For input string: "1s"错误的解决办法(图文详解)

    不多说,直接上干货 问题详情 [kfk@bigdata-pro01 apache-hive--bin]$ bin/hive Logging initialized -bin/conf/hive-log ...