ServletContext

web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;

1、共享数据

​ 在这个Servlet中保存了数据,就可以在另外一个servlet取到

首先将数据存入HelloServlet中,然后可以在另外一个Servlet类中取出

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter() //初始化参数
//this.getServletConfig() Servlet配置
//this.getServletContext() Servlet 上下文 ServletContext context = this.getServletContext(); String name = "逍遥子";//数据
context.setAttribute("name",name);//将一个数据保存在了 ServletContext 中
System.out.println("数据已经存放!!!!");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
@WebServlet("/getc")
public class ReadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//数据
ServletContext context = this.getServletContext();
String name = (String) context.getAttribute("name");
//响应,设置编码
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字"+name);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

2、获取初始化参数

可以获得在xml中初始化保存的参数

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置一些web应用的初始化参数 -->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param> </web-app>
@WebServlet("/gp")
public class ServletDeom03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//数据
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

3、请求转发

转发并不会改变请求的路径,重定向才会改变请求的路径

转发是间接获取到资源,重定向是直接拿到资源

@WebServlet("/sd4")
public class Servletdemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//数据
System.out.println("进入了demo04页面");
ServletContext context = this.getServletContext();
//RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发路径
//requestDispatcher.forward(req,resp);//调用forward实现请求转发
context.getRequestDispatcher("/gp").forward(req,resp);//请求转发
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

4、读取资源文件

Properties

  • 在java目录下新建properties
  • 在resource目录下新建properties

发现:都被打包到了同一路径下:classes,我们俗称这个路径为classpath

注:在java目录下创建的properties文件,若想导出成功,还需配置xml文件

<!--  在build中配置resource,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

读文件思路:需要一个文件流;

@WebServlet("/sd5")
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /**
* 1、导入properties流,根据项目的相对地址
* 2、创建properties对象
* 3、将刚刚的流加载到properties对象中
* 4、成功引入properties文件
*/
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
resp.getWriter().print("username = "+username);
resp.getWriter().print("password = "+password);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

ServletContext 学习的更多相关文章

  1. Servlet-Context学习笔记

    介绍 ServletContext其实就是全局作用域对象, 上下文环境对象 利用context可以实现对,当前网站中所有的Servlet共享数据 context对象只能由Tomcat负责创建,在tom ...

  2. servletconfig和servletcontext学习

    servletconfig java.lang.String getInitParameter(java.lang.String name)  //根据参数名获取参数值 java.util.Enume ...

  3. spring定时器中如何获取servletcontext

    spring定时器中如何获取servletcontext 学习了:https://zhidao.baidu.com/question/406212574.html @Scheduled(cron = ...

  4. [原创]java WEB学习笔记47:Servlet 监听器简介, ServletContext(Application 对象), HttpSession (Session 对象), HttpServletRequest (request 对象) 监听器,利用listener理解 三个对象的生命周期

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  5. Servlet的学习之ServletContext(2)

    本篇接上篇<Servlet的学习(五)>,继续从ServletContext对象中的方法进行学习,在这一篇中,我们重点关注的是ServletContext对象中对于在web工程中的资源文件 ...

  6. Servlet、ServletConfig、ServletContext深入学习

    1.Servlet学习 1.Servlet生命周期 Servlet 加载—>实例化—>服务—>销毁. init(servletConfig):(经过自己的测试发现会先调用这个而不是i ...

  7. Servlet学习(二):ServletConfig获取参数;ServletContext应用:请求转发,参数获取,资源读取;类装载器读取文件

    转载:http://www.cnblogs.com/xdp-gacl/p/3763559.html 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件 ...

  8. [原创]java WEB学习笔记06:ServletContext接口

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  9. 重温Servlet学习笔记--servletContext对象

    一个项目中只有一个ServletContext对象,我们可以在多个servlet中获取这个唯一的对象,使用它可以给多个servlet传递数据,我们通常成servletContext为上下文对象.这个对 ...

随机推荐

  1. ES6中class的继承

    extends 子类的继承 super(); 调用父类的构造方法,只能在子类中执行 继承可以让子类获得父类的方法 属性,可以扩充 增加新的方法 属性等 父类(基类)--被继承的类 子类--继承后的类 ...

  2. C++、Java、Python、Linux、Go、前端、算法,慕课资料分享

    C++.Java.Python.Linux.Go.前端.算法,慕课资料分享 微信公众号:大道同行JAVA 如有问题或建议,请后台留言,我会尽力解决你的问题. 前言 又见面了.废话不多说,最近多了一些在 ...

  3. C# - 习题02_写出程序的输出结果a.Fun()

    时间:2017-08-23 整理:byzqy 题目:写出程序的输出结果: 文件:Program.cs 1 using System; 2 3 namespace Interview1 4 { 5 pu ...

  4. 由Eratosthenes筛法演变出的一种素数新筛法

    这两天和walls老师交流讨论了一个中学竞赛题,我把原题稍作增强和变形,得到如下一个题: 从105到204这100个数中至少要选取多少个数才能保证选出的数中必有两个不是互素的? 我们知道最小的几个素数 ...

  5. SpringBoot 属性配置文件数据注入配置和yml与properties区别

    前言 我们知道SpringBoot 通过配置类来解放一堆的xml文件配置,通属性配置文件,来进行,系统全局属性配置,这样极大的简化了我们开发过程,java web 也可以甜甜的从此 快速配置 Spri ...

  6. Hexo+Butterfly主题美化

    前言 本博客基于Hexo框架搭建,用到 hexo-theme-butterfly 主题(本人博客Butterfly版本3.4.0),hexo-theme-butterfly是基于Molunerfinn ...

  7. Python - repr()、str() 的区别

    总的来说 str():将传入的值转换为适合人阅读的字符串形式 repr():将传入的值转换为 Python 解释器可读取的字符串形式 传入整型 # number resp = str(1) print ...

  8. Python - 文件模式a+读取不了文件

    代码 f = open('test/gbk.txt', 'a+', encoding='utf-8') print(f.readline()) 最终的执行结果是输出空,为什么呢? a+模式打开文件指针 ...

  9. python库--pandas--DataFrame

    转换    索引,迭代    运算符    功能应用,分组及窗口    计算/描述统计 重新索引/选择/标签操作    缺失数据处理    形状变换/排序/转置 组合/加入/合并    时间序列相关  ...

  10. project read error(项目读取错误)

    maven的pom文件出现project read error 1,打开电脑cmd操作界面,在cmd界面找到打开出错项目的文件夹; 比如我的项目文件夹在D:\>eclipse-jee-file\ ...