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

Servlet基础_0500_Application

2011-09-28 21:53 274 查看
一.application概念:

application即ServletContext,能够被所有的客户端页面共享,不同的浏览器,不同电脑上的浏览器

演示:

//ServletContextTest.java

package com.servlet;

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;

public class ServletContextTest extends HttpServlet {

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

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
//这块内存可以被所有客户端共享
ServletContext application = this.getServletContext();
Integer count = (Integer)application.getAttribute("accessCount");
if(count==null){
count = new Integer(0);
}else{
count ++;
}
application.setAttribute("accessCount", count);
out.println(count);
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doGet(request, response);
}

}

将这个页面配置好,访问: http://localhost:8080/Servlet_0500_Application/ServletContextTest ,不断刷新,发现数值在增长;换个浏览器,重新访问,发现值还在增加

注意application实际上指的是ServletContext接口,HttpServlet继承自GenericServlet,GenericServlet实现了ServletConfig接口,ServletConfig接口中有个getServletContext()的抽象方法,ServletContext application = this.getServletContext(),得到的就是这个ServletContext具体实现。

证明application是能被所有的客户端共享的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: