day15-Servlet04( 三 )

浏览器访问ServletContext_:

day15-Servlet04

文章插图
后台输出:
day15-Servlet04

文章插图
13.4.2应用实例2-简单的网站访问次数统计器需求:完成一个简单的网站访问次数统计器
不管使用什么浏览器,每访问一次Servlet , 就增加1访问次数,在后台输出 , 并将结果返回给浏览器显示
day15-Servlet04

文章插图
WebUtils.java:
package com.li.servlet.servletcontext;import javax.servlet.ServletContext;public class WebUtils {//该方法对访问网站的次数累加,同时返回次数public static Integer visitCount(ServletContext servletContext) {//从servletContext获取 visit_count 属性 k-vObject visit_count = servletContext.getAttribute("visit_count");//判断visit_count是否为空if (visit_count == null) {//说明是第1次访问网站servletContext.setAttribute("visit_count", 1);visit_count = 1;} else {//说明是第二次或之后访问//visit_count+1visit_count = Integer.parseInt(visit_count + "") + 1;//再将其放回servletContextservletContext.setAttribute("visit_count", visit_count);}return Integer.parseInt(visit_count + "");}}Servlet01.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 = {"/Servlet01"})public class Servlet01 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();}}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

文章插图

推荐阅读