Servlet-ServletContext对象

概述

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

共享数据

Set

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取上下文容器
    ServletContext context = this.getServletContext();
    // 将一个数据保存在了ServletContext中,键值对形式,名字为:data,值: 你好
    context.setAttribute("data", "你好");

    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    response.getWriter().print("Have set!");
}

Get

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取上下文容器
    ServletContext context = this.getServletContext();
    // 根据key获取值
    String data = (String) context.getAttribute("data");

    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    response.getWriter().print("data:" + data);
}

验证

Servlet-ServletContext对象

先获取值会得到null值:

Servlet-ServletContext对象

Servlet-ServletContext对象

获取初始化参数

web.xml:

<!--配置一些web应用初始化参数-->
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取上下文容器
    ServletContext context = this.getServletContext();
    // 获取web.xml中预配置的参数
    String url = context.getInitParameter("url");

    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    response.getWriter().print("data:" + url);
}

测试

Servlet-ServletContext对象

请求转发

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取上下文容器
    ServletContext context = this.getServletContext();
    // 重定向到 /hello
    context.getRequestDispatcher("/hello").forward(request, response);
}

测试

Servlet-ServletContext对象

读取资源文件

新建资源文件

Servlet-ServletContext对象

重新生成项目

确保配置好pom,防止导出资源失败

Servlet-ServletContext对象

Servlet-ServletContext对象

复制资源文件路径

Servlet-ServletContext对象

代码

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取输入流
    InputStream is = this.getServletContext().getResourceAsStream("WEB-INF/classes/db.properties");
    // 加载Properties文件
    Properties prop = new Properties();
    prop.load(is);
    // 获取值
    String username = prop.getProperty("username");
    String password = prop.getProperty("password");

    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    response.getWriter().print("username:" + username);
    response.getWriter().print("<br/>");
    response.getWriter().print("password:" + password);
}

测试

Servlet-ServletContext对象

上一篇:./yy.sh -d bash 执行脚本时所加的参数


下一篇:13 Servlet——session案例2:用户登录主页显示用户名和注销登录