ServletContext是Servlet容器上下文环境对象,定义一组方法,servlet 使用这些方法与其 servlet 容器进行通信,例如,获取文件的 MIME 类型、分发请求或写入日志文件。
每个web应用都有且仅有一个ServletContext对象,这个对象在所有的Servlet都可以使用。
ServletContext 对象包含在ServletConfig 对象中,ServletConfig 对象在初始化Servlet 时由Web 服务器提供给Servlet。
ServletContext在jsp中用application内置对象来表示,而在Servlet中通过调用方法
ServletContext sc = getServletContext();
因为一个web应用就一个ServletContext 对象,因此可以使用ServletContext 来做一些全局性的属性设置等。比如网站访问计数器等等。下面给出一个简单的页面计数器:
<body>
<%
Integer x = (Integer) application.getAttribute( "num");
if (x == null) {
application.setAttribute( "num", 1);
} else {
application.setAttribute( "num", ++x);
}
out.println( "您是第"+x+ "位访客!");
%>
</body>
<%
Integer x = (Integer) application.getAttribute( "num");
if (x == null) {
application.setAttribute( "num", 1);
} else {
application.setAttribute( "num", ++x);
}
out.println( "您是第"+x+ "位访客!");
%>
</body>
ServletContext与ServletConfig的区别:
获取资源绝对路径:
getServletContext().getRealPath(
"/");
上面的代码可以返回应用程序部署绝对路径。
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/275588,如需转载请自行联系原作者