javaweb学习(7)--Application servletContext

Posted by lizhao on 09-16,2016
这个是针对一整个webapp,所有窗口都共享的。

代码如下

public class ApplicationServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();

        //拿到的是整个上下文
        ServletContext servletContext = this.getServletContext();
        Integer accessCount = (Integer) servletContext.getAttribute("accessCount");
        if(accessCount==null){
            accessCount=new Integer(0);
        }else{
            accessCount=new Integer(accessCount.intValue()+1);
        }
        servletContext.setAttribute("accessCount", accessCount);
        writer.println("<h3>accessCount:"+accessCount+"</h3>");

    }
}