application对象直接包装了servlet的ServletContext类的对象,是javax.servlet.ServletContext 类的实例。

这个对象在JSP页面的整个生命周期中都代表着这个JSP页面。这个对象在JSP页面初始化时被创建,随着jspDestroy()方法的调用而被移除。

通过向application中添加属性,则所有组成您web应用的JSP文件都能访问到这些属性。


方法 描述
设置  
void setAttribute(String name,Object obj) 设定属性的属性值
void log(String msg) 把指定消息写入Servlet的日志文件
void log(Exception exception,String msg) 把指定异常的栈轨迹及错误消息写入Servlet日志文件
void log(String msg,Throwable throwable) 把栈轨迹及Throwable异常信息写入Servlet日志文件
返回  
Object getAttribute(String name) 返回给定名的属性值
Enumeration getAttributeNames() 返回所有可用属性名的枚举
String getServerInfo() 返回JSP(Servlet)引擎名及版本号
String getRealPath(String path) 返回一虚拟路径的真实路径
ServletContext getContext(String uripath) 返回指定WebApplication的application对象
int getMajorVersion() 返回服务器支持的Servlet API的最大版本号
int getMinorVersion() 返回服务器支持的Servlet API的最大版本号
String getMimeType(String file) 返回指定文件的MIME类型
URL getResource(String path) 返回指定资源(文件及目录)的URL路径
InputStream getResourceAsStream(String path) 返回指定资源的输入流
RequestDispatcher getRequestDispatcher(String uripath) 返回指定资源的RequestDispatcher对象
Servlet getServlet(String name) 返回指定名的Servlet
Enumeration getServlets() 返回所有Servlet的枚举
Enumeration getServletNames() 返回所有Servlet名的枚举
删除  
void removeAttribute(String name) 删除一属性及其属性值

示例

application.setAttribute("name","li");//设置


Date now = new Date();
application.setAttribute("now",now);//设置


application.setAttribute("count","100");
Integer count = (Integer)application.getAttribute("count");//获取,(Integer)强制转换类型


application.removeAttribute("name");//删除


Enumeration names = application.getAttributeNames();//获取所有对象
while(names.hasMoreElements()){//遍历
	out.println(names.nextElement()+"<br>");
}



注:后端Servlet中使用需先获取ServletContext对象

ServletContext application = this.getServletContext();//获得ServletContext对象
out.println( application.getRealPath("/") );