day15-Servlet04( 四 )

Servlet02.java:
package com.li.servlet.servletcontext;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;import java.io.PrintWriter;@WebServlet(urlPatterns = {"/Servlet02"})public class Servlet02 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取到ServletContext对象ServletContext servletContext = getServletContext();Integer visit_count = WebUtils.visitCount(servletContext);//输出显示response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.print("<h1>该网站被访问的次数是" + visit_count + "</h1>");writer.flush();writer.close();}}redeployTomcat,在不同的浏览器分别访问Servlet01和Servlet02:

day15-Servlet04

文章插图

经验总结扩展阅读