文章目录
- 一、 ServletContext
-
- 1.1 介绍
- 1.2 共享数据
- 1.3 获取初始化参数
- 1.4 请求转发
- 1.5 读取文件
学习视频来自于:秦疆(遇见狂神说)Bilibili地址
他的自学网站:kuangstudy
我们缺乏的不是知识,而是学而不厌的态度一、 ServletContext 1.1 介绍 web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
1.2 共享数据 我在ServletContextDemo1 保存数据,可以在ServletContextDemo2 中取出
public class ServletContextDemo1 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "https://www.it610.com/article/xdp_gacl";
/**
* ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
* 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
*/
ServletContext context = this.getServletConfig().getServletContext();
//获得ServletContext对象
context.setAttribute("data", data);
//将data存储到ServletContext对象中
}public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class ServletContextDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
String data = https://www.it610.com/article/(String) context.getAttribute("data");
//从ServletContext对象中取出数据
response.getWriter().print("data="https://www.it610.com/article/+data);
}public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
1.3 获取初始化参数
username
root
ServletContext context = this.getServletContext();
String username = context.getInitParameter("username");
resp.getWriter().println(username);
1.4 请求转发 请求转发
浏览器地址栏不变
重定向
浏览器地址栏该表
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");
// 转发的路径
requestDispatcher.forward(req,resp);
// 调用forward实现请求转发
1.5 读取文件 【JavaEE|ServletContext(运行环境信息)】使用Properties类
- 在resources目录下新建properties文件
- 配置文件被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
InputStream is = context.getResourceAsStream("WEB-INF/classes/mysql.properties");
Properties pro = new Properties();
pro.load(is);
String className = pro.getProperty("driverClassName");
resp.getWriter().println("driverClassName:"+className);
}
推荐阅读
- java|P1009 [NOIP1998 普及组] 阶乘之和
- Mybatis|Mybatis XML动态SQL
- 【Java面试】什么是 ISR,为什么需要引入 ISR
- #|向上转型和向下转型
- 开发技能点|Sentinel 概述
- web前端|web前端day01
- web前端|web前端day05
- web前端|web前端day07
- Java基础|Java基础.Java编译过程