JavaWeb开发基础:Application的知识点简述
Application的概念比较简单,相比cookie(只允许客户端访问),session(一个客户端只能访问特定的session内存),但是application里面的内存是可以供所有的客户端访问的内容。
比如,我们想要知道某一时段访问这个服务器的客户端有多少。
我们常规的做法有:
- 插入数据库
- 写入文件
- 写入application里面
现在,就简单说说application这个东西。
context的概念:
context里面有很多webapplication,每一个application里面运行很多servlet。
每一个web application运行的环境叫做context,翻译做中文叫做 上下文。
他的概念上非常抽象。可以称作web application在内存中运行的表现。
利用application:
application是一块可以让所有客户端访问的公用的内存,那么我们可以做一些事情比如记录访客数量等不隐私的活动。
代码示例如下:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.Date;
public class TestServletContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
//拿到内存中属于所有客户端的内存
ServletContext application = this.getServletContext();
Integer accessCount = (Integer) application.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
} else {
accessCount = new Integer(accessCount.intValue() + 1);
}
// Use setAttribute instead of putValue in version 2.2.
application.setAttribute("accessCount", accessCount);
out.println("<html><head><title>Session追踪</title></head>"
+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">"
+ accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>"
+ "</H1>\n");
}
}
ServletContext application = this.getServletContext();
上面这串代码,获取了servlet中的application。这里直接调用父类httpservlet的方法。
getServletContext()
setServletContext()
这两个方法和session的使用都差不多。注意键值对的名一定是String。