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.获取初始化的参数

<!--配置一些web应用初始化参数--> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-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(); }
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术