案例(web开发):统计用户访问的次数(Servlet对象)

案例分析:

原理:init方法只会在创建Servlet对象的时候执行一次

  1. 用户第一次访问Servlet
    重写init方法,获取ServletContext域对象,存储一个键值对count记录访问次数(只会执行一次)
    在doGet方法中,获取到域对象中存储的count
    把count给用户响应回去
    count++
    把count存储到ServletContext域对象
  2. 用户不是第一次访问Servlet
    在doGet方法中,获取到域对象中存储的count
    把count给用户响应回去
    count++
    把count存储到ServletContext域对象

代码实现:

package com.ccc.demo01ServletContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/count")
public class Demo06CountServlet extends HttpServlet {
    //重写init方法,获取ServletContext域对象,存储一个键值对count记录访问次数(只会执行一次)
    @Override
    public void init() throws ServletException {
        ServletContext context = getServletContext();
        context.setAttribute("count",1);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //在doGet方法中,获取到域对象中存储的count
        ServletContext context = getServletContext();
        int count = (int)context.getAttribute("count");
        //把count给用户响应回去
        response.getWriter().write("welcome\t"+count);
        //count++
        count++;
        //把count存储到ServletContext域对象
        context.setAttribute("count",count);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
如果直接输出count是不行的,比如
response.getWriter().write(count);

因为浏览器是不认识整数的,只能把它变为字符串输出才行。比如在前面或者后面加一个空格

response.getWriter().write(" "+count);

猜你喜欢

转载自blog.csdn.net/qq_45083975/article/details/92442950