您的位置:首页 > 移动开发

Servlet学习(七)Application

2016-07-19 14:51 337 查看
Session是服务器内,针对某个特定客户端(浏览器)的特定内存区域。

而Application是在webapp生命周期内,提供给所有客户端的服务器内的内存区域。

Application在API中对应类ServletContext。

context:上下文,一个context相当一个webapp的运行环境。两者一一对应。

servletContext通过HttpServlet的getServletContext()方法就可以拿到,

通过ServletContext的getAttribute()和setAttribute()方法获取/设置相关属性。

测试程序:

package com.vin.application;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Application测试
* 用于保存整个web应用的生命周期内都可以访问的数据
* 可供多个不同窗口访问,可作为某一页面被总共访问次数的计数器(比如网站首页的访问量)
* @author Pigeon
*
*/
public class TestServletContext extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();

// Returns a reference to the ServletContext in which this servlet is running.
ServletContext application = this.getServletContext();
// 从当前application中读取属性accessCount的值
Integer accessCount = (Integer)application.getAttribute("accessCount");
if(accessCount == null) {
accessCount = new Integer(0);
} else {
accessCount = new Integer(accessCount.intValue() + 1);
}
// 向当前application中插入键(key,属性)值(value)对
application.setAttribute("accessCount", accessCount);

out.println("<html><head><title>ServletContext测试</title></head><br>"
+ "<body><td>" + accessCount +"</td>/n"
+ "</body></html>");

}

}结果:每次刷新,访问次数+1.
与session不同的是,session刷新页面,访问次数+1。但重新打开页面,访问次数归零。(关闭页面即关闭旧session,打开新session)

application刷新页面,访问次数+1;重新打开页面,访问次数不归零。(application的context上下文存货于整个webapp的生命周期)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: