ServletContext类 (共享数据+获取初始化的参数+请求转发+读取资源文件)


ServletContext对象

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

作用

1.共享数据  (一般用session)

//在servlet1 存

ServletContext context = this.getServletContext();
        String username = "Kant"; //数据
        context.setAttribute("username",username); //将一个数据保存在ServletContext中,名字为:username 。值 username
       


// 在servlet2 取

ServletContext context = this.getServletContext();
 String username = (String) context.getAttribute("username");

2.获取初始化的参数


<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql://localhost:3306/mybatisparam-value>
context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}

3.请求转发(请求A界面,实际是访问B界面,虽然URL不变)

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了ServletDemo04");
//RequestDispatcher requestDispatcher =
context.getRequestDispatcher("/gp"); //转发的请求路径
//requestDispatcher.forward(req,resp); //调用forward实现请求转发;
context.getRequestDispatcher("/gp").forward(req,resp);
}


请求去A界面,实际被转发到了/gp界面

4.读取资源文件

 InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/aa.properties");
        //这个路径可以在target目录下找到生成的对应文件
        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");
        resp.getWriter().print(user+":"+pwd);
        is.close();
    }