[Jweb] Application / TestServletContext.java

  ServletContext Servlet 上下文,指的就是 Servlet 怎么和它的运行环境打交道。
  Servlet 所处的是什么环境呢?其实是tomcat。
  ServletContext application = this.getServletContext();
  application 这个篮子比Session大。webapp 下所有的 servlet 访问的都是这同一个篮子。

  示例程序 : TestServletContext.java
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">
" + "<H1 ALIGN="CENTER">"
                + accessCount + "
" + "</TABLE>
" + "</BODY></HTML>"
                + "</H1>
");

    }
}

原文地址:https://www.cnblogs.com/robbychan/p/3786868.html