[Jweb] Application / TestServletContext.java

来源:互联网 发布:淘宝供应商在哪里解除 编辑:程序博客网 时间:2024/05/21 21:02
  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\">\n" + "<H1 ALIGN=\"CENTER\">"                + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>"                + "</H1>\n");    }}

0 0
原创粉丝点击