《Oracle Java EE编程指南》10-02:ServletContext接口

ServletContext接口

Servlet API中定义了ServletContext接口,用来封装上下文对象
该接口中定义了一系列的方法:

序号 名称 简介 简介
01 void setAttribute(String key,Object value) 以key/value的形式保存对象值
02 Object getAttribute(String key) 通过key获取对象值
03 String getInitParameter(String path) 返回上下文参数的值
04 String getRealPath(String path) 根据虚拟路径返回实际路径(参看ch02中的使用)

如何获得ServletContext对象

ServletContext是接口,不能直接创建对象。ServletContext对象是容器创建的,可以使用Servlet API中提供的方法获取该对象。
Servlet类中常用的获取上下文对象的方法

  • ServletConfig接口中定义的getServletContext方法
  • 由于自定义的Servlet类间接实现了ServletConfig接口,因此可以直接调用getServletContext方法返回ServletContext对象
    JSP文件中使用上下文对象的方法
  • JSP文件的内置对象application即上下文对象,可以调用ServletContext接口中的任意方法

猜你喜欢

转载自blog.csdn.net/goldentec/article/details/105337094