Count the number of times a user visits (Servlet objects): Case (web development)

case study:

Principle: the init method is executed only once when creating the Servlet object

  1. A user first visits Servlet
    override the init method, obtaining ServletContext domain objects, storing a key-value pair count the number of visits recorded (only once)
    in doGet method, the acquired domain objects stored count
    to count the response back to the user
    count ++
    to count objects stored in the ServletContext domain
  2. Servlet not the first time the user accessed
    in the doGet method, gets into the domain objects stored in the count
    to count the response back to the user
    count ++
    to count objects stored in the ServletContext domain

Code:

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);
    }
}
If the direct output count does not work, such as
response.getWriter().write(count);

Because the browser does not know integers, you can only turn it into a string output the job. For example, in front of or behind a space

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

Guess you like

Origin blog.csdn.net/qq_45083975/article/details/92442950